美文网首页
go 学习笔记

go 学习笔记

作者: 西门吹牛々 | 来源:发表于2018-03-17 13:06 被阅读9次
  • go build、go install 和 go run 的区别
go build 编译包,如果是main包则在当前目录生成可执行文件,其他包不会生成.a文件;
go install 编译包,同时复制结果到$GOPATH/bin,$GOPATH/pkg等对应目录下;
go run gofiles... 编译列出的文件,并生成可执行文件然后执行。注意只能用于main包,否则会出现go run: cannot run non-main package的错误。
go run是不需要设置$GOPATH的,但go build和go install必须设置。
go run常用来测试一些功能,这些代码一般不包含在最终的项目中
  • 格式化代码
gofmt –w *.go
  • go get本质
可以理解为首先第一步是通过源码工具clone代码到src下面, 然后执行 go install
  • 初始化值
// 初始化1
type person struct {
  name string
  age int
} 
var P person // P现在就是person类型的变量了
P.name = "Astaxie" // 赋值"Astaxie"给P的name属性.
P.age = 25 // 赋值"25"给变量P的age属性
//按照顺序提供初始化值
P := person{"Tom", 25}
//通过 field:value 的方式初始化, 这样可以任意顺序
P := person{age:24, name:"Tom"}
// 当然也可以通过 new 函数分配一个指针, 此处P的类型为*person
P := new(person)
  • 声明自定义类型
type ages int
type money float32
type months map[string]int
m := months {
"January":31,
"February":28,
...
"December":31,
}
  • golang中根据首字母的大小写来确定可以访问的权限。无论是方法名、常量、变量名还是结构体的名称,如果首字母大写,则可以被其他的包访问;如果首字母小写,则只能在本包中使用
  • 指针
如果一个method的receiver是*T,你可以在一个T类型的实例变量V上面调用这个method, 而不需要&V去调用这个method类似的
如果一个method的receiver是T, 你可以在一个T类型的变量P上面调用这个method, 而不需要 P去调用这个method
所以, 你不用担心你是调用的指针的method还是不是指针的method, Go知道你要做的一切。
  • 实现多态

package main

import (
    "fmt"
    "math"
)

type rectangle struct {
    width, height float64
}
type circle struct {
    radius float64
}
type square struct {
    width float64
}

func (r rectangle) area() float64 {
    return r.width * r.height
}
func (c circle) area() float64 {
    return c.radius * c.radius * math.Pi
}
func (s square) area() float64 {
    return s.width * s.width
}

func main() {
    r1 := rectangle{12, 2}
    r2 := rectangle{9, 4}
    c1 := circle{10}
    c2 := circle{25}
    s1 := square{5}
    fmt.Println("Area of r1 is: ", r1.area())
    fmt.Println("Area of r2 is: ", r2.area())
    fmt.Println("Area of c1 is: ", c1.area())
    fmt.Println("Area of c2 is: ", c2.area())
    fmt.Println("Area of s1 is: ", s1.area())
}

相关文章

网友评论

      本文标题:go 学习笔记

      本文链接:https://www.haomeiwen.com/subject/nqzhqftx.html