Files
build-web-application-with-…/2.4.md
2012-08-28 23:32:25 +08:00

50 lines
1.3 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#2.4 高级类型
##strcut
Go语言中也和C或者其他语言中一样我们可以声明新的类型作为其它类型的属性或字段的容器。例如我们可以创建一个自定义类型`person`代表一个人的实体。这个实体拥有属性:姓名和年龄。这样的类型我们称之`struct`。如下代码所示:
type person struct {
name string
age int
}
看到了吗申明一个strcut如此简单上面的类型包含有两个字段
- 一个string类型的字段name用来保存用户名称这个属性
- 一个int类型的字段age,用来保存用户年龄这个属性
如何使用strcut呢请看下面的代码
type person struct {
name string
age int
}
var P person // P现在就是person类型的变量了
P.name = "Astaxie" //赋值"Astaxie"给P的name属性.
P.age = 25 //赋值"25"给变量P的age属性
fmt.Println("The person's name is %s", P.name) // 访问P的name属性.
除了上面这种P的申明使用之外还有两种申明使用方式
- 1.按照顺序提供初始化值
P := person{"Tom", 25}
- 2.通过`field:value`的方式初始化,这样可以任意顺序
P := person{age:24, name:"Tom"}
##interface
## links
* [目录](<preface.md>)
* 上一章: [流程和函数](<2.3.md>)
* 下一节: [面向对象](<2.5.md>)
## LastModified
* $Id$