feat: struct embedding, enums
This commit is contained in:
46
go-by-example/enums/enums.go
Normal file
46
go-by-example/enums/enums.go
Normal file
@@ -0,0 +1,46 @@
|
||||
package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
type ServerState int
|
||||
|
||||
const (
|
||||
StateIdle ServerState = iota
|
||||
StateConnected
|
||||
StateError
|
||||
StateRetrying
|
||||
)
|
||||
|
||||
var stateName = map[ServerState]string{
|
||||
StateIdle: "idle",
|
||||
StateConnected: "connected",
|
||||
StateError: "error",
|
||||
StateRetrying: "retrying",
|
||||
}
|
||||
|
||||
// String Changes the output value
|
||||
func (ss ServerState) String() string {
|
||||
return stateName[ss]
|
||||
}
|
||||
|
||||
func main() {
|
||||
ns := transition(StateIdle)
|
||||
fmt.Println(ns)
|
||||
|
||||
ns2 := transition(ns)
|
||||
fmt.Println(ns2)
|
||||
}
|
||||
|
||||
func transition(s ServerState) ServerState {
|
||||
switch s {
|
||||
case StateIdle:
|
||||
return StateConnected
|
||||
case StateConnected, StateRetrying:
|
||||
|
||||
return StateIdle
|
||||
case StateError:
|
||||
return StateError
|
||||
default:
|
||||
panic(fmt.Errorf("unknown state: %s", s))
|
||||
}
|
||||
}
|
||||
40
go-by-example/structs/struct-embedding/struct-embedding.go
Normal file
40
go-by-example/structs/struct-embedding/struct-embedding.go
Normal file
@@ -0,0 +1,40 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
)
|
||||
|
||||
type base struct {
|
||||
num int
|
||||
}
|
||||
|
||||
func (b base) describe() string {
|
||||
return fmt.Sprintf("base with num=%v", b.num)
|
||||
}
|
||||
|
||||
type container struct {
|
||||
base
|
||||
str string
|
||||
}
|
||||
|
||||
func main() {
|
||||
co := container{
|
||||
base: base{
|
||||
num: 1,
|
||||
},
|
||||
str: "Some name",
|
||||
}
|
||||
fmt.Printf("co={num: %v, str: %v}\n", co.num, co.str)
|
||||
|
||||
fmt.Println("also num: ", co.base.num) // also num but can be without
|
||||
|
||||
// co can also use base method describe since it emebeds base
|
||||
fmt.Println("describe: ", co.describe())
|
||||
|
||||
var d describer = co
|
||||
fmt.Println("describer:", d.describe())
|
||||
}
|
||||
|
||||
type describer interface {
|
||||
describe() string
|
||||
}
|
||||
Reference in New Issue
Block a user