-
Define a struct and its method
type Parent struct { Id int Name string } func (p Parent) GetName() string { return p.Name } func (p *Parent) SetName(name string) { p.Name = name }
p
forGetName
is a receiver.p
forSetName
is a pointer receiver, which is used to modify value of the receiver.
Exercise: Pointer Receiver
-
Use the new struct.
func main() { p := Parent{Id: 1, Name: "John"} fmt.Println(p) p.SetName("Bob") fmt.Println(p.GetName()) }
-
Run.
go run main.go {1 John} Bob
-
Embed
Parent
struct inChild
struct.type Child struct { Parent // Embed Parent struct OtherField string }
-
Child
can use theParent
's methods.func main() { p := Parent{Id: 1, Name: "John"} ch := Child{Parent: p} fmt.Printf("id: %d, name: %s\n", ch.Id, ch.Name) ch = Child{Parent{Id: 1, Name: "child"}, "Other"} fmt.Println(ch.GetName()) }
-
Run.
go run main.go id: 1, name: John child
Embedding is often used in Kubernetes operator too!
Example: memcached_controller.go
type MemcachedReconciler struct {
client.Client // Embeded
Scheme *runtime.Scheme
Recorder record.EventRecorder
}
In this example, MemcachedReconciler
has all the methods of client.Client such as Get
, Create
, Update
, etc.
-
Define an interface
Product
type Object interface { GetName() string }
-
Use it.
func main() { p := Parent{Id: 1, Name: "John"} printObjectName(&p) ch := Child{Parent: p} printObjectName(&ch) ch = Child{Parent{Id: 1, Name: "child"}, "Other"} printObjectName(&ch) } func printObjectName(obj Object) { fmt.Println(obj.GetName()) }
-
Run.
go run main.go John John child