1、结构体定义
package main
import "fmt"
// 类型
type myint int
// 结构体
type Book struct {
title string
auth string
}
func updbook(book Book) {
book.auth = "小明"
}
func updbookPr(book *Book) {
book.auth = "小明"
}
func main() {
var a myint = 10
fmt.Println("a=",a)
fmt.Printf("type of a = %T\n",a)
var book Book;
book.title = "标题"
book.auth = "作者"
fmt.Println("init :",book)
//修改
updbook(book)
fmt.Println("upd auth :",book)
//修改
updbookPr(&book)
fmt.Println("upd auth pr:",book)
}
结果:
2、类定义
package main
import "fmt"
//定义一个结构体
type People struct{
id string
name string
}
//----------------------------------------------
//定义一个方法,绑定结构体People
func (this People) show() {
fmt.Println("id = ",this.id)
fmt.Println("name =",this.name)
}
//getName
func (this People) getName() string {
return this.name
}
//setName
func (this People) setName(fName string) {
this.name = fName
}
//--------------------------------------------
//定义一个方法,绑定结构体People
func (this *People) showPr() {
fmt.Println("id = ",this.id)
fmt.Println("name =",this.name)
}
//getName
func (this *People) getNamePr() string {
return this.name
}
//setName
func (this *People) setNamePr(fName string) {
this.name = fName
}
func main() {
//定义一个对象
p := People{id: "p1",name: "小明"}
p.show()
p.setName("小红")
p.show()
p.setNamePr("小红")
p.showPr()
}
结果: