[Turn] go in struct initialization of three ways

https://www.cnblogs.com/leisure520/p/7745691.html

----------------------------------------------------------------

GO language other than the language in a struct, it has no constructor, but also do not have to assign no error.

such as:

Copy the code
type Student struct {
    name string
    age  int
}

func main() {

    var P Student

    fmt.Println("The person's name is", P.name)
    fmt.Println("The person's name is", P.age)
}
Copy the code

This is why, because when naming a type of time, string it is empty by default, int type defaults to 0, float64 it defaults to 0.0 ,.

When initialized, there are several ways lingua franca:

The first:

    var P Student
    P.name = "Huang"
    P.age = 12
    fmt.Println("The person's name is", P.name)
    fmt.Println("The person's name is", P.age)

 

Second, direct:

    var P Student = Student{"huang", 15}

    fmt.Println("The person's name is", P.name)
    fmt.Println("The person's name is", P.age)

Third:

P := new(person)

Note that the third words represent a new pointer

Guess you like

Origin www.cnblogs.com/oxspirt/p/12381354.html