21

面向"对象" - day 2

 4 years ago
source link: https://www.tuicool.com/articles/ee2e2ui
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

结构体和方法

函数的定义和声明

type treeNode struct {
    value int
    left, right *treeNode
}
func main() {
    var root treeNode
    root = treeNode{value: 3}
    root.left = &treeNode{}
    root.right = &treeNode{5, nil, nil}
    root.right.left = new(treeNode)
    // struct slice
    nodes := []treeNode {
        {value: 3},
        {},
        {5, nil, nil}
    }
}

Goang 中可以将局部变量的地址返回使用

结构的方法

func (node treeNode) print() {
//...
}
func main() {
    node.print()
}

go语言中结构方法的接收参数也是值传递,如果想修改则需要传递地址指针;但是在结构方法调用时不需要取地址,编译器会自动判断转换的;在结构方法内部也不需要使用 * 进行转换,直接使用 . 进行访问属性就可以

只有使用指针才可以改变结构内容

nil指针也可以调用方法

值接收者 vs 指针接收者

  • 要改变内容必须使用指针接收者
  • 结构过大也考虑使用指针接收者
  • 一致性:如有指针接收者,最好都是指针接收者

包和封装

  • 每个目录有且只能有一个包(包名字可以与目录名不同)
  • 为结构体定义的方法可以在不同的文件,但是必须在同一个包内

Golang 中结构体的名字不需要重复包的名字

扩展已有类型

  • 定义别名
  • 使用组合

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK