Go Language Learning Note 10: Structure
The structure syntax of the go language is similar to the C language. The concept of structs is similar to the class in high-level language java.
Definition of structural body
The struct has two keyword type and struct, and a struct name is sandwiched between the two. All the member variables are written in curly braces, and the types of these variables are specified. Use the. Symbol when accessing these internal members. Note that a variable created by a struct is used to access internal members with a point.
is not accessed directly by the struct.
package mainimport "fmt"type Book struct { name string price int}func main() { var book1 Book; var book2 Book; book1.name = "书名1" book1.price = 100 book2 = Book {"书名2", 200} fmt.Printf( "Book 1 name : %s\n", book1.name) fmt.Printf( "Book 1 price : %d\n", book1.price) fmt.Printf( "Book 2 : %s\n", book2)}
struct as function parameter
func printBook( book Book ) { fmt.Printf( "Book name : %s\n", book.name); fmt.Printf( "Book price : %d\n", book.price)}
struct-Body pointer
var x *Bookx = &book1;x.name;
Both struct pointers and struct variables are used. To access internal members. It feels more cumbersome to use a pointer operation.
Go Language Learning Note 10: Structure