import导入的三种形式
支持绝对路径和相对路径
- 
.操作,类似于js中的import 模块goimport ( . "fmt" ) //使用时可省略模块名前缀: Printf("key:%v value=%v;", k, v)
- 
别名操作,类似于 import b as c from "b"goimport ( f "fmt" ) f.Printf("key:%v value=%v;", k, v)
- 
_操作,调用包里面的init函数goimport ( "database/sql" _ "github.com/ziutek/mymysql/godrv" )
结构体:struct
声明新的类型,作为其它类型的属性或字段的容器
- 
声明和初始化 gotype person struct { name string age int } P.name = "Astaxie" // 赋值"Astaxie"给P的name属性. P.age = 25 // 赋值"25"给变量P的age属性 fmt.Printf("The person's name is %s", P.name) // 访问P的name属性. // 也可以使用下面几种方式进行初始化 // 1.按声明顺序初始化 P:=person{"jack",26} // 2. 通过failed:value初始化 P := person{age:24, name:"Tom"} // 3. 通过new声明一个指针 P:= new(person)
- 
匿名字段,嵌入式字段,即: 继承gopackage main import ( f "fmt" ) type commonResponse struct { code string msg string } type loginInfoData struct { token string userId string userName string phone string } type loginInfo struct { commonResponse data loginInfoData } func main() { loginRes := loginInfo{ commonResponse{ code: "10000", msg: "success", }, loginInfoData{ userId: "123456", token: "tttttooooXXXXKKKKK", userName: "皮皮虾", phone: "16543432076", }, } f.Println(loginRes.code) f.Println(loginRes.data) }
面向对象
method
类似js中的class,go中没有
this,声明函数时可以定义接收者,这种函数称作method
            
            
              go
              
              
            
          
          package main
import (
	f "fmt"
)
const (
	WHITE = iota
	BLACK
	BLUE
	RED
	YELLOW
)
type Color byte
type Box struct {
	width, height int
	color         Color
}
func (r Box) area() int {
	return r.height * r.width
}
func (r *Box) setColor(color Color) {
	r.color = color
	f.Printf("setColor:%v\n", r)
}
func main() {
	box1 := Box{
		10,
		20,
		YELLOW,
	}
	box1.setColor(WHITE)
	box2 := Box{
		6,
		7,
		BLACK,
	}
	f.Println(box1.area())
	f.Println(box2.area())
	f.Println(box1)
}使用method的时候要注意几点:
- 虽然method的名字一模一样,但是如果接收者不一样,那么method就不一样
- method里面可以访问接收者的字段
- 调用method通过.访问,就像struct里面访问字段一样
- method 不仅可以用在struct上,还可以定义在任何类型上
下面两个是不同的method
            
            
              go
              
              
            
          
          func (r Rectangle) area() float64 {
	return r.width*r.height
}
func (c Circle) area() float64 {
	return c.radius * c.radius * math.Pi
}指针作为接收者
默认情况下,传递给method的是接收者的一个copy,如果想要修改接收者,需要传递指针过去,例如上面例子中的setColor方法
method继承的继承
如果匿名字段实现了一个method,那么包含这个匿名字段的struct也能调用该method