Menu
CoddyTech

结构体值

Coddy 面向 Ruby 开发者的 Go 课程的第 25 课,共 48 课。

Ruby 的类对象、new 和 initialize 会创建引用对象。Go 的结构体是值,而 New 风格的工厂函数是普通函数。Go 没有类对象、initialize 钩子或自动调用构造函数的机制。只有在有意共享标识并进行修改时,才使用指针。

结构体将具有固定类型的命名字段组合在一起。键控字面量会指定要设置的字段;省略的字段会使用零值。赋值会复制结构体值,不过其中的指针、切片和映射字段仍可能引用共享数据。

Ruby 示例

class Parcel
  attr_accessor :label
end
parcel = Parcel.new
parcel.label = 'sample'
puts parcel.label

源代码输出:

sample

Go 示例

package main
import ("fmt")
type Label struct { Text string }
func main(){a:=Label{Text:"old"}
b:=a
b.Text="new"
fmt.Println(a.Text,b.Text)}

Go 输出:

old new
challenge icon

挑战

简单

定义 Pair,并包含导出的 int 字段 Left 和 Right。Solve 返回它们的和。输入 x 和 y,每个各占一行。

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

你的代码写在 pair.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)
a1:=I(1); before1:=fmt.Sprint(a1)
p:=Pair{Left:4,Right:9}; q:=p; q.Left=0; must(p.Left==4 && p.Right==9,"struct value");
result:=Solve(a0,a1)
must(fmt.Sprint(a0)==before0,"input mutation")
must(fmt.Sprint(a1)==before1,"input mutation")
fmt.Println(result)
}
quiz icon自我测试

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

面向 Ruby 开发者的 Go中的所有课

自己练习: Go 在线编译器