1、结构体定义
package mainimport "fmt"// 类型type myint int// 结构体type Book struct {title stringauth string}func updbook(book Book) {book.auth = "小明"}func updbookPr(book *Book) {book.auth = "小明"}func main() {var a myint = 10fmt.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 mainimport "fmt"//定义一个结构体type People struct{id stringname string}//----------------------------------------------//定义一个方法,绑定结构体Peoplefunc (this People) show() {fmt.Println("id = ",this.id)fmt.Println("name =",this.name)}//getNamefunc (this People) getName() string {return this.name}//setNamefunc (this People) setName(fName string) {this.name = fName}//--------------------------------------------//定义一个方法,绑定结构体Peoplefunc (this *People) showPr() {fmt.Println("id = ",this.id)fmt.Println("name =",this.name)}//getNamefunc (this *People) getNamePr() string {return this.name}//setNamefunc (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()}
结果:
