构造函数惯例
Coddy 面向 C# 开发者的 Go 课程的第 28 课,共 48 课。
C# 构造函数会初始化一个新类或结构体,并且可能抛出异常。Go 中类似构造函数的函数是普通函数,通常返回 (*T,error)。Go 没有构造函数重载,也不要求必须调用构造函数才能使用可见结构体的零值。
Go 没有专门的构造函数语法。NewType 函数是一种约定,也可能返回错误。不要让无效状态出现在返回值中。返回指针可以提供共享标识,而对于较小的不可变记录,返回值也可能是合适的。
C# 示例
using System;
using System.Collections.Generic;
using System.Linq;
class Greeting{public string Text;public Greeting(string name){Text="Hello "+name;}}
class Program { static void Main() {
Console.WriteLine(new Greeting("Ada").Text);
} }源代码输出:
Hello AdaGo 示例
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挑战
简单实现 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)
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 C# 开发者的 Go中的所有课
自己练习: Go 在线编译器