Struct
This commit is contained in:
parent
27cf79ba61
commit
b35ac2c1c9
1 changed files with 56 additions and 0 deletions
56
2moretypes/struct.go
Normal file
56
2moretypes/struct.go
Normal file
|
@ -0,0 +1,56 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
)
|
||||
|
||||
type Vertex struct {
|
||||
X int
|
||||
Y int
|
||||
}
|
||||
|
||||
func main() {
|
||||
|
||||
fmt.Println("A struct is a collection of fields")
|
||||
fmt.Println(Vertex{1, 2})
|
||||
|
||||
fmt.Println("struct fields are accessed by using a dot")
|
||||
v := Vertex{6, 8}
|
||||
fmt.Printf("%T, %v\n", v, v)
|
||||
fmt.Printf("%T, %v\n", v.X, v.X)
|
||||
fmt.Printf("%T, %v\n", v.Y, v.Y)
|
||||
|
||||
fmt.Printf("\n\n")
|
||||
|
||||
fmt.Println("Struct fields can be accessed through a struct pointer")
|
||||
v2 := Vertex{6, 8}
|
||||
p := &v2
|
||||
// var p *Vertex = &v2 // ALSO VALID
|
||||
|
||||
(*p).X = 10
|
||||
fmt.Printf("%T, %v, %p\n", p, p, p)
|
||||
fmt.Printf("%T, %v\n", *p, *p)
|
||||
|
||||
fmt.Println("Go also allows to use struct pointers without * symbol while accesing elements:")
|
||||
p.X = 15 // VALID
|
||||
fmt.Println(*p)
|
||||
|
||||
fmt.Printf("\n\n")
|
||||
|
||||
fmt.Println("You can also use struct literals for assigning struct elements")
|
||||
var (
|
||||
v3 = Vertex{10, 20}
|
||||
v4 = Vertex{X: 1} // Y:0
|
||||
v5 = Vertex{} // X:0, Y:0
|
||||
v6 = Vertex{Y: 15, X: 75}
|
||||
p2 = &Vertex{1, 2}
|
||||
)
|
||||
|
||||
fmt.Printf("%T, %v\n", v3, v3)
|
||||
fmt.Printf("%T, %v\n", v4, v4)
|
||||
fmt.Printf("%T, %v\n", v5, v5)
|
||||
fmt.Printf("%T, %v\n", v6, v6)
|
||||
fmt.Printf("%T, %v\n", p2, p2)
|
||||
fmt.Printf("%T, %v\n", *p2, *p2)
|
||||
|
||||
}
|
Loading…
Reference in a new issue