GO语言结构体,与java类相似,但也有不同之处
package main
import (
"fmt"
)
//Rect fields
type Rect struct {
width int//声明字段名称
height int
}
//Area function
func (r *Rect) Area() int {//添加类中的方法
//添加方法与其他语言有所不同,添加方法是在结构体外添加
return r.width * r.height
}
func main() {
rect := &Rect{100, 200}
fmt.Println(rect.Area())//调用方法
}
GO语言声明结构体
type structname struct{
width int//字段名称
height int
}
func (n *structname) Add() int {
//首先方法名前的(n *structname)表示自定义指针,当访问内部字段时,使用n.fieldsname访问字段
return r.width*r.height
}
func main(){
tstruct :=&structname{100,200}
//初始化结构体方法有多种,只是其中一种,其他方法,在下面介绍
fmt.Println(tstruct.Add())
}
结构体初始化有很多种
type test struct{
width int
heght int
}
test1:=new(test)
test2:=&test{}
test3:=&test{100,200}
test4:=&test{width:100,height:200}