1、结构体定义

    1. package main
    2. import "fmt"
    3. // 类型
    4. type myint int
    5. // 结构体
    6. type Book struct {
    7. title string
    8. auth string
    9. }
    10. func updbook(book Book) {
    11. book.auth = "小明"
    12. }
    13. func updbookPr(book *Book) {
    14. book.auth = "小明"
    15. }
    16. func main() {
    17. var a myint = 10
    18. fmt.Println("a=",a)
    19. fmt.Printf("type of a = %T\n",a)
    20. var book Book;
    21. book.title = "标题"
    22. book.auth = "作者"
    23. fmt.Println("init :",book)
    24. //修改
    25. updbook(book)
    26. fmt.Println("upd auth :",book)
    27. //修改
    28. updbookPr(&book)
    29. fmt.Println("upd auth pr:",book)
    30. }

    结果:
    image.png
    2、类定义

    1. package main
    2. import "fmt"
    3. //定义一个结构体
    4. type People struct{
    5. id string
    6. name string
    7. }
    8. //----------------------------------------------
    9. //定义一个方法,绑定结构体People
    10. func (this People) show() {
    11. fmt.Println("id = ",this.id)
    12. fmt.Println("name =",this.name)
    13. }
    14. //getName
    15. func (this People) getName() string {
    16. return this.name
    17. }
    18. //setName
    19. func (this People) setName(fName string) {
    20. this.name = fName
    21. }
    22. //--------------------------------------------
    23. //定义一个方法,绑定结构体People
    24. func (this *People) showPr() {
    25. fmt.Println("id = ",this.id)
    26. fmt.Println("name =",this.name)
    27. }
    28. //getName
    29. func (this *People) getNamePr() string {
    30. return this.name
    31. }
    32. //setName
    33. func (this *People) setNamePr(fName string) {
    34. this.name = fName
    35. }
    36. func main() {
    37. //定义一个对象
    38. p := People{id: "p1",name: "小明"}
    39. p.show()
    40. p.setName("小红")
    41. p.show()
    42. p.setNamePr("小红")
    43. p.showPr()
    44. }

    结果:
    image.png