Skip to content

Instantly share code, notes, and snippets.

@alf-ytakada
Created January 11, 2022 07:58
Show Gist options
  • Save alf-ytakada/e226843176995796a5c68191e56d4d35 to your computer and use it in GitHub Desktop.
Save alf-ytakada/e226843176995796a5c68191e56d4d35 to your computer and use it in GitHub Desktop.
nil has type, it can be a receiver.
package main
import "fmt"
type A struct {
a string
}
func NewA(strp *string) *A {
if strp == nil {
return nil
}
return &A{a: *strp}
}
func (a *A) GetA() *string {
if a == nil {
return nil
}
return &a.a
}
func main() {
str := "hello"
a1 := NewA(&str)
fmt.Printf("a1: %#v, a1.GetA() = %#v\n", a1, a1.GetA()) // a1: &main.A{a:"hello"}, a1.GetA() = (*string)(0xc000010250)
a2 := NewA(nil)
fmt.Printf("a2: %#v, a2.GetA() = %#v\n", a2, a2.GetA()) // a2: (*main.A)(nil), a2.GetA() = (*string)(nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment