MENU

Go 学习笔记:结构体

August 23, 2021 • Read: 81 • Golang

go也提供了结构体这个功能,具体实现也很类似与C语言

声明结构体

/*
 * @Author: NorthCityChen
 * @LastEditTime: 2021-08-23 15:09:20
 * @Description:
 * @Website: https://grimoire.cn
 * Copyright (c) NorthCityChen All rights reserved.
 */
package main

import (
    "fmt"
)

type character struct {
    name string
    star int
}

func main() {
    var ch1 character = character{name: "shenli", star: 5}
    ch2 := character{"leidian", 5}
    fmt.Println(ch1)
    fmt.Println(ch2)
}

亦或者是访问里面的成员变量

/*
 * @Author: NorthCityChen
 * @LastEditTime: 2021-08-23 15:13:19
 * @Description:
 * @Website: https://grimoire.cn
 * Copyright (c) NorthCityChen All rights reserved.
 */
package main

import (
    "fmt"
)

type character struct {
    name string
    star int
}

func main() {
    var ch1 character = character{name: "shenli", star: 5}
    ch2 := character{"leidian", 5}
    fmt.Println(ch1.name)
    fmt.Println(ch1.star)
    fmt.Println(ch1.name)
    fmt.Println(ch2.star)
}

当然,也可以作为参数传入函数内

/*
 * @Author: NorthCityChen
 * @LastEditTime: 2021-08-23 15:14:58
 * @Description:
 * @Website: https://grimoire.cn
 * Copyright (c) NorthCityChen All rights reserved.
 */
package main

import (
    "fmt"
)

type character struct {
    name string
    star int
}

func main() {
    var ch1 character = character{name: "shenli", star: 5}
    ch2 := character{"leidian", 5}
    getInfo(ch1)
    getInfo(ch2)
}

func getInfo(ch character) {
    fmt.Println(ch.name)
    fmt.Println(ch.star)
}

学了结构体,简单写一个单向链表

/*
 * @Author: NorthCityChen
 * @LastEditTime: 2021-08-23 16:31:46
 * @Description:
 * @Website: https://grimoire.cn
 * Copyright (c) NorthCityChen All rights reserved.
 */
package main

import (
    "fmt"
)

type node struct {
    value int
    next  *node
}

type linkList struct {
    length int
    next   *node
    tail   *node
}

func main() {
    list := createLinkList()
    createNode(list, 2)
    createNode(list, 3)
    createNode(list, 7)

    forEach(*list)
}

func createLinkList() *linkList {
    return &linkList{length: 0}
}

func createNode(curLinkList *linkList, value int) int {
    tail := curLinkList.tail
    newNode := &node{value: value}
    length := curLinkList.length + 1
    if tail == nil {
        curLinkList.tail = newNode
        curLinkList.next = newNode
    } else {
        curNode := curLinkList.tail
        curLinkList.tail = newNode
        curNode.next = newNode
    }
    curLinkList.length = length
    return length

}

func forEach(curLinkList linkList) int {
    curNode := curLinkList.next
    fmt.Println(curNode.value)
    for curNode.next != nil {
        curNode = curNode.next
        fmt.Println(curNode.value)
    }
    return curLinkList.length
}
Archives Tip
QR Code for this page
Tipping QR Code