Skip to content

Latest commit

 

History

History

03-interface-and-struct

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 

Interface and Struct

1. Struct

  1. 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
    }
    1. p for GetName is a receiver.
    2. p for SetName is a pointer receiver, which is used to modify value of the receiver.

    Exercise: Pointer Receiver

  2. Use the new struct.

    func main() {
        p := Parent{Id: 1, Name: "John"}
        fmt.Println(p)
        p.SetName("Bob")
        fmt.Println(p.GetName())
    }
  3. Run.

    go run main.go
    {1 John}
    Bob
    

2. Embedding

  1. Embed Parent struct in Child struct.

    type Child struct {
        Parent // Embed Parent struct
        OtherField string
    }
  2. Child can use the Parent'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())
    }
  3. Run.

    go run main.go
    id: 1, name: John
    child
    

Example

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.

Interface

  1. Define an interface Product

    type Object interface {
        GetName() string
    }
  2. 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())
    }
  3. Run.

    go run main.go
    John
    John
    child
    

References

  1. Structs and Interfaces
  2. Method Pointer Receivers in Interfaces

Practices

  1. Structs
  2. Struct Fields
  3. Pointer Receiver
  4. Interfaces
  5. Interfaces are implemented implicitly
  6. Interface values
  7. Interface values with nil underlying values
  8. Nil interface values
  9. The empty interface
  10. Type assertions
  11. Type switches
  12. Stringers
  13. Exercise: Stringers