type user1 struct {
name string
Age int
}
type user2 struct {
name string
age int
sex time.Time
}
type User struct {
u1 user1 //别名
user2
Name string
Age int
}
func main() {
var user User
user.Name = "nick"
user.u1.Age = 18
fmt.Println(user) //{{ 18} { 0 {0 0 <nil>}} nick 0}
}
tag
在go中,首字母大小写有特殊的语法含义,小写包外无法引用。由于需要和其它的系统进行数据交互,例如转成json格式。这个时候如果用属性名来作为键值可能不一定会符合项目要求。tag在转换成其它数据格式的时候,会使用其中特定的字段作为键值。
import "encoding/json"
type User struct {
Name string `json:"userName"`
Age int `json:"userAge"`
}
func main() {
var user User
user.Name = "nick"
user.Age = 18
conJson, _ := json.Marshal(user)
fmt.Println(string(conJson)) //{"userName":"nick","userAge":0}
}
String()
如果实现了String()这个方法,那么fmt默认会调用String()。
type name1 struct {
int
string
}
func (this *name1) String() string {
return fmt.Sprintf("This is String(%s).", this.string)
}
func main() {
n := new(name1)
fmt.Println(n) //This is String().
n.string = "suoning"
d := fmt.Sprintf("%s", n) //This is String(suoning).
fmt.Println(d)
}
接口Interface
Interface类型可以定义一组方法,但是这些不需要实现。并且interface不能包含任何变量。
interface类型默认是一个指针。
Interface定义
type Car interface {
NameGet() string
Run(n int)
Stop()
}
Interface实现
Golang中的接口,不需要显示的实现。只要一个变量,含有接口类型中的所有方法,那么这个变量就实现这个接口。因此,golang中没有implement类似的关键字;
如果一个变量含有了多个interface类型的方法,那么这个变量就实现了多个接口;如果一个变量只含有了1个interface的方部分方法,那么这个变量没有实现这个接口。
空接口 Interface{}:空接口没有任何方法,所以所有类型都实现了空接口。
var a int
var b interface{} //空接口
b = a
多态
一种事物的多种形态,都可以按照统一的接口进行操作。
栗子:
type Car interface {
NameGet() string
Run(n int)
Stop()
}
type BMW struct {
Name string
}
func (this *BMW) NameGet() string {
return this.Name
}
func (this *BMW) Run(n int) {
fmt.Printf("BMW is running of num is %d n", n)
}
func (this *BMW) Stop() {
fmt.Printf("BMW is stop n")
}
type Benz struct {
Name string
}
func (this *Benz) NameGet() string {
return this.Name
}
func (this *Benz) Run(n int) {
fmt.Printf("Benz is running of num is %d n", n)
}
func (this *Benz) Stop() {
fmt.Printf("Benz is stop n")
}
func (this *Benz) ChatUp() {
fmt.Printf("ChatUp n")
}
func main() {
var car Car
fmt.Println(car) // <nil>
var bmw BMW = BMW{Name: "宝马"}
car = &bmw
fmt.Println(car.NameGet()) //宝马
car.Run(1) //BMW is running of num is 1
car.Stop() //BMW is stop
benz := &Benz{Name: "大奔"}
car = benz
fmt.Println(car.NameGet()) //大奔
car.Run(2) //Benz is running of num is 2
car.Stop() //Benz is stop
//car.ChatUp() //ERROR: car.ChatUp undefined (type Car has no field or method ChatUp)
}









