Menu
CoddyTech

构造函数惯例

Coddy 面向 C++ 开发者的 Go 课程的第 28 课,共 48 课。

C++ RAII 将资源的生命周期与对象销毁和作用域绑定。Go 的垃圾回收负责管理内存,而不会及时释放外部资源。成功获取资源后,使用显式的 Close 风格方法,并通过 defer 延后调用。要有意分配彼此独立的实例集合;复制结构体仍可能共享切片或映射。

Go 没有专门的构造函数语法。NewType 函数是一种约定,也可以返回错误。不要让无效状态出现在返回值中。返回指针可以提供共享的标识,而对于小型不可变记录,返回值也可能更合适。

C++ 示例

#include <algorithm>
#include <iomanip>
#include <iostream>
#include <map>
#include <numeric>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>
int main() {
    struct Score {
        int points;
        explicit Score(int initial = 0) : points(initial) {}
    };
    Score a(5), b;
    std::cout << a.points << ' ' << b.points << '\n';
}

源代码输出:

5 0

Go 示例

package main
import ("fmt")
type Greeting struct { Text string }; func NewGreeting(name string) Greeting { return Greeting{Text:"Hello "+name} }
func main(){p:=NewGreeting("Ada")
fmt.Println(p.Text)}

Go 输出:

Hello Ada
challenge icon

挑战

简单

实现 NewAccount(balance int) (*Account,error)。余额为负时返回 nil 和非 nil 错误;其他余额则返回一个账户,其 Balance() 与余额相符。输入一个余额。

实现声明的 API;返回结果,不要打印。驱动程序会检查所需的 API,并保留调用方的输入。集合的标准输出使用 Go 的方括号格式,而不是 JSON。

你的代码写在 account.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)
a,e:=NewAccount(7); must(e==nil && a!=nil && a.Balance()==7,"constructor API"); a,e=NewAccount(-1); must(a==nil && e!=nil,"constructor rejection");
result:=Solve(a0)
must(fmt.Sprint(a0)==before0,"input mutation")
fmt.Println(result)
}
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

面向 C++ 开发者的 Go中的所有课

自己练习: Go 在线编译器