xxxxxxxxxx
package main
import "fmt"
type User struct {
Name string
}
func main() {
var x1 string
x1 = "jane doe"
var x2 *string
x2 = &x1
x3 := "max cavalera"
x4 := &x3
x5 := User{Name: "john doe"}
x6 := &x5
fmt.Println(*x2)
fmt.Println(*x4)
fmt.Println((*x6).Name) // or call like this *&x6.Name
}
xxxxxxxxxx
p := Vertex{1, 2} // p is a Vertex
q := &p // q is a pointer to a Vertex
r := &Vertex{1, 2} // r is also a pointer to a Vertex
// The type of a pointer to a Vertex is *Vertex
var s *Vertex = new(Vertex) // new creates a pointer to a new struct instance
xxxxxxxxxx
func main() {
i, j := 42, 2701
p := &i // point to i
fmt.Println(*p) // read i through the pointer
*p = 21 // set i through the pointer
fmt.Println(i) // see the new value of i
p = &j // point to j
*p = *p / 37 // divide j through the pointer
fmt.Println(j) // see the new value of j
}
xxxxxxxxxx
package main
import "fmt"
func main() {
// create a normal string variable
name := "original"
// pass in a pointer to the string variable using '&'
setName(&name, "boot.dev")
fmt.Println(name)
}
func setName(ptr *string, newName string) {
// dereference the pointer so we can modify the value
// and set the value to "boot.dev"
*ptr = newName
}
xxxxxxxxxx
// Program to assign memory address to pointer
package main
import "fmt"
func main() {
var name = "John"
var ptr *string
// assign the memory address of name to the pointer
ptr = &name
fmt.Println("Value of pointer is", ptr)
fmt.Println("Address of the variable", &name)
}
xxxxxxxxxx
p := Vertex{1, 2} // p is a Vertex
q := &p // q is a pointer to a Vertex
r := &Vertex{1, 2} // r is also a pointer to a Vertex
// The type of a pointer to a Vertex is *Vertex
var s *Vertex = new(Vertex) // new creates a pointer to a new struct instance