GO语言自学_006_类的访问权限

一、访问权限规则规则

1、在go语言中,权限都是通过首字母大小写控制的。
2、import中,如果包不同,大写字母才是public。
3、类中成员和方法,大写开头才能被其他包使用。

二、案例

三、可复制代码

1、Aninal.go
package src

import "fmt"

/*
0、在go语言中,权限都是通过首字母大小写控制的。
1、import中,如果包不同,大写字母才是public。
2、类中成员和方法,大写开头才能被其他包使用。
*/

// 定义一个Animal类

type Animal struct {
  // Animal的属性
  Name   string
  Age    int
  Gender string
  Color  string
  Legs   int
}

type Doggo struct {
  // Doggo 特有的属性
  Animal
  Food  string
  Owner string
}

// 外部绑定一个方法

func (a *Animal) Eat() {
  fmt.Println("this is ", a.Name, ", he/she eats.")
}

2、main.go
package main

import "04_struct_permit/src"

func main() {
  doggo1 := src.Doggo{
    Animal: src.Animal{
      Name:   "happy",
      Age:    2,
      Gender: "male",
      Color:  "Red",
      Legs:   4,
      },
      Food:  "bones",
      Owner: "Julie",
    }
    println("doggo1 调用了继承的Animal的类:", doggo1.Age)
    println("doggo1 调用了本身的Doggo的类:", doggo1.Food)
    doggo1.Eat()
}

3、结果

GOROOT=C:\Program Files\Go #gosetup
GOPATH=C:\gowork #gosetup
"C:\Program Files\Go\bin\go.exe" build -o C:\Users\ASUS\AppData\Local\Temp\GoLand\___go_build_04_struct_permit.exe 04_struct_permit #gosetup
C:\Users\ASUS\AppData\Local\Temp\GoLand\___go_build_04_struct_permit.exe
doggo1 调用了继承的Animal的类: 2
doggo1 调用了本身的Doggo的类: bones
this is  happy , he/she eats.

Process finished with the exit code 0

posted @ 2022-09-05 16:20  顺心无忧  阅读(95)  评论(0编辑  收藏  举报