导出与封装
Coddy 面向 C# 开发者的 Go 课程的第 37 课,共 48 课。
C# 私有成员属于声明它们的类型上下文。Go 中以小写字母开头的名称不会从包中导出,但可在包内的多个文件之间共享。Go 没有 private、protected 或 public 关键字,也没有特定于类的隐私边界。
以大写字母开头的名称会从其所属包中导出。小写字母表示包私有,而不是文件私有或实例私有。公共方法可以维护不变量,但同一包中的文件仍然可以访问内部字段。此练习检查的是行为,而不是对其所属包的保密性。
C# 示例
using System;
using System.Collections.Generic;
using System.Linq;
class Session{private bool active=false;public bool Active(){return active;}}
class Program { static void Main() {
Console.WriteLine(new Session().Active());
} }源代码输出:
FalseGo 示例
package main
import ("fmt")
type Session struct{active bool};func(s Session)Active()bool{return s.active}
func main(){s:=Session{}
fmt.Println(s.Active())}
Go 输出:
false挑战
简单实现 Box,其中包含未导出的 value int、用于存储 max(n,0) 的 Set(n int),以及 Get() int。新声明的 Box 初始值为零。主程序会探测多次更新。
实现已声明的 API;返回结果,不要打印。驱动程序会检查所需的 API,并保留调用方的输入。集合的标准输出使用 Go 的方括号格式,而不是 JSON。
你的代码写在 box.go、exercise.go 中。main.go 包含提供的输入/输出代码,不能编辑。保持只有一个扁平的 package main;不要添加第二个 main。
亲手试试
package main
import ("fmt";"strings";"strconv";"bufio";"os")
var input []string
func L(i int)string{if i<len(input){return input[i]};return ""}
func I(i int)int{n,e:=strconv.Atoi(L(i));if e!=nil{panic(e)};return n}
func Ints(i int)[]int{out:=[]int{};if L(i)==""{return out};for _,s:=range strings.Split(L(i),","){n,e:=strconv.Atoi(s);if e!=nil{panic(e)};out=append(out,n)};return out}
func Words(i int)[]string{if L(i)==""{return []string{}};return strings.Split(L(i),",")}
func must(ok bool,message string){if !ok{panic("API: "+message)}}
func main(){
scanner:=bufio.NewScanner(os.Stdin);for scanner.Scan(){input=append(input,scanner.Text())};if scanner.Err()!=nil{panic(scanner.Err())}
a0:=I(0); before0:=fmt.Sprint(a0)
b:=Box{};must(b.Get()==0,"zero Box");b.Set(7);must(b.Get()==7,"Box Set");b.Set(-1);must(b.Get()==0,"Box clamp");
result:=Solve(a0)
must(fmt.Sprint(a0)==before0,"input mutation")
fmt.Println(result)
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 C# 开发者的 Go中的所有课
自己练习: Go 在线编译器