Skip to content

Instantly share code, notes, and snippets.

@ObsidianCat
Last active July 15, 2023 10:22
Show Gist options
  • Save ObsidianCat/fcb55c0f3c517259fda955900d4a8126 to your computer and use it in GitHub Desktop.
Save ObsidianCat/fcb55c0f3c517259fda955900d4a8126 to your computer and use it in GitHub Desktop.
Different meaning of * Sign in Go, based on situation
package main
import "fmt"
type person struct {
name string
}
// the * denotes(indicate) a pointer to a value of the type that follows the *
// *person the func return pointer
func createPersonRef(name string) *person {
// The & operator generates a pointer to its operand
return &person{name}
}
func main() {
// When you print a pointer to a struct with fmt.Println, it doesn't print the memory address
// (like it would for a pointer to an int or a string), but instead prints the struct's fields.
// This is because fmt.Println uses reflection to print values, and it treats pointers to structs as a special case.
ref := createPersonRef("John")
fmt.Println(ref) // &{John}
fmt.Println(&ref) // 0xc0000ae018
fmt.Println(*ref) // {John} the * is the dereference operator. It gives the value that the pointer points to.
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment