Go

定义

go 语言中的struct与c的很相似,此外,go没有Class,也没有继承。

stuct的格式为:type <name> struct{}

package main

import (
    "fmt"
)

type person struct {
    Name string
    Age  int
}

func main() {
    p := person{
        Name: "Tony",
        Age:  23,
    }
    fmt.Println(p)
}
//output
{Tony 23}

Struct是值类型

package main

import (
    "fmt"
)

type person struct {
    Name string
    Age  int
}

func ChangeAge(per person) {
    per.Age = 15
    fmt.Printf("Call 'Change Age' function, new age is %d 
", per.Age)
}

func main() {
    p := person{
        Name: "Tony",
        Age:  23,
    }
    fmt.Println(p)
    ChangeAge(p)
    fmt.Println(p)
}

//output
{Tony 23}
Call 'Change Age' function, new age is 15 
{Tony 23}

我们可以看到,age属性只在func内部被修改,因此可以确定struct是值类型(传递给函数的参数为值的一个copy)

如何传递引用?

我们可以将函数的参数类型定义称为“一个指针”,即可

package main

import (
    "fmt"
)

type person struct {
    Name string
    Age  int
}

func ChangeAge(per *person) {
    per.Age = 15
    fmt.Printf("Call 'Change Age' function, new age is %d 
", per.Age)
}

func main() {
    p := person{
        Name: "Tony",
        Age:  23,
    }
    fmt.Println(p)
    ChangeAge(&p)
    fmt.Println(p)
}

//output
{Tony 23}
Call 'Change Age' function, new age is 15 
{Tony 15}

struct中的匿名字段

go 语言中,支持在struct中省略字段的名称,只保留其类型(匿名字段)

package main

import (
    "fmt"
)

type person struct {
    string
    int
}

func main() {
    p := person{
        "Bob",
        27,
    }
    fmt.Println(p)
}

// output
{Bob 27}

匿名结构

go语言中,也支持定义匿名结构。

package main

import (
    "fmt"
)

func main() {
    p := struct {
        Name string
        Age  int
        Sex  string
    }{
        Name: "Joe",
        Age:  26,
        Sex:  "female",
    }
    fmt.Println(p)
}

//output
{Joe 26 female}

使用嵌入字段来“模拟”继承关系

package main

import (
    "fmt"
)

type person struct {
    Sex string
}

type teacher struct {
    person
    Name string
    Age  int
}

func main() {
    t := teacher{
        person: person{Sex: "feamle"},
        Name:   "Jill",
        Age:    28,
    }
    fmt.Println(t)

    t.Age = 30
    t.Name = "Criss"
    t.person.Sex = "male"
    fmt.Println(t)
}

//output
{{feamle} Jill 28}
{{male} Criss 30}
原文地址:https://www.cnblogs.com/atuotuo/p/6884908.html