← Back to articles

Learning Go (9): structs and methods

Part 9 of my Go fundamentals notes: syntax, examples, and lessons learned.

Structs

1. The type keyword

The type keyword is used for:

Declaring structs

Declaring interfaces

Declaring type aliases

Defining new types

Type switches and assertions use related type syntax

1.1. Type aliases

Aliases can clarify intent and improve readability. An alias denotes the original type rather than creating a distinct type.

//以定义int的别名举例
type MyInt = int
var i MyInt
fmt.Println("%T\n", i)
//上面代码输出的结果为int,相当一给int取了一个小名,MyInt本质上还是int

1.2. Defined types

A defined type is a new type based on an existing underlying type, such as int, string, or a struct. A struct underlying type can contain multiple named fields. This lets us represent more specific data structures.

type MyInt int // 相比于类型别名,没有等号
var i MyInt
fmt.Println("%T\n", i)
//上面代码输出的结果为xxxx.MyInt

Why define a new type?

We can give it methods and express its intended use more clearly.

func (mi MyInt) string() string{
    return strconv.Itoa(int(mi))
}

func main(){
    var i MyInt = 10
    fmt.Println(i.string())
}
// 上面的代码给MyInt增加了一个string方法,这样就可以将MyInt类型转换为string类型

2. Declaring and initializing structs

Go combines the simplicity of C-style structs with methods that support object-oriented organization.

For personal information such as name, age, address, and mobile number, define a struct like this:

type Person struct{
    name string
    age int
    address string
    mobile string
}

func main(){
    //结构体的初始化方式
    p1 := Person{"小明", 18, "北京", "13812345678"} //省略写法每个元素都要写
    p2 := Person{name: "小红", age: 19, address: "上海", mobile: "13812345679"} //能够填部分元素,更灵活
    var p3 Person
    p3.name = "小刚"

    var persons []Person
    persons = append(persons, p1)
    persons = append(persons, Person{"小刚", 20, "广州", "13812345680"})
}

3. Anonymous structs

Use an anonymous struct for a temporary, one-off grouping of fields.

address := struct{
    province string
    city string
    district string
}{
    "北京",
     "北京", 
     "海淀区"
}
fmt.Println(address.city)

4. Nested structs

One struct can contain another struct as a field.

type Person struct{
    name string
    age int
}
// 可以不用重复定义
type Student struct{
    // 第一种嵌套方式
    p Person
    score float32
}

func main() {
    // 第一种初始化方式
    s := Student{
        p: Person{
            name: "小明",
            age: 18,
        },
        score: 90,
    }
    fmt.Println(s.p.name)

    // 第二种初始化方式
    s := Student{}
    s.p.name = "小明"
}

Embedded fields

type Person struct{
    name string
    age int
}
// 可以不用重复定义
type Student struct{
    // 第二种嵌套方式--匿名嵌套
    Person
    score float32
}

func main() {
    // 初始化方式
    s.name = "小明"
}

5. Methods on structs

Define a method for a struct type.

In Go, method declarations are written outside the struct declaration.

type Person struct{
    name string
    age int
}

func (p Person) print(){
    fmt.Printf("姓名:%s, 年龄:%d\r\n", p.name, p.age)
}

func main() {
    p := Person{
        name: "小明",
        age: 18,
    }
    p.print()
}

Use a pointer receiver when a method needs to modify the original struct’s fields.

type Person struct{
    name string
    age int
}

func (p *Person) print(){
    p.age = 19
    fmt.Printf("姓名:%s, 年龄:%d\r\n", p.name, p.age)
}

func main() {
    p := Person{
        name: "小明",
        age: 18,
    }
    p.print()
}
//此时输出的结果为:姓名:小明, 年龄:19
About this article’s date

The date recorded on the old site is retained; writing may have started earlier.

In this series · Go fundamentals

PreviousLearning Go (8): functions, defer, and errors ←NextLearning Go (10): pointers and nil →