导出与封装
Coddy 面向 C++ 开发者的 Go 课程的第 37 课,共 48 课。
C++ 的私有字段和 getter 方法可以强制执行不变量。Go 中以小写字母开头的名称会限制其他包的访问,但不会限制同一包中的其他文件。必须让调用者维护状态时,应公开方法,而不是可变字段。String 方法可以提供格式化功能,无需重载流运算符。
以大写字母开头的名称会从所属包中导出。小写名称表示包内私有,而非文件私有或实例私有。公有方法可以强制执行不变量,但同一包中的文件仍然可以访问内部字段。本练习检查的是行为,而不是对所属包内部的保密性。
C++ 示例
#include <algorithm>
#include <iomanip>
#include <iostream>
#include <map>
#include <numeric>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>
int main() {
struct Meter {
int level;
explicit Meter(int value) : level(value) {
if (value < 0) throw std::invalid_argument("negative");
}
};
Meter meter(3);
std::cout << "level=" << meter.level << '\n';
}源代码输出:
level=3Go 示例
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,其中包含未导出的 int 类型 value、用于存储 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 在线编译器