golang学习笔记——struct结构体
定义
type 变量名 struct{
元素1名称 元素1类型
元素2名称 元素2类型
}
package main
import (
"fmt"
)
type student struct {
id int
name string
age int
addr string
}
func main() {
//顺序初始化 每个元素必须都设置
s1 := student{1, "mayuan", 26, "tianjin"}
fmt.Println("s1 = ", s1)
//指定元素赋值,其他元素默认0
s2 := student{name: "mayuan", age: 26}
fmt.Println("s2 = ", s2)
}
操作成员使用(.)运算符
package main
import (
"fmt"
)
type student struct {
id int
name string
age int
addr string
}
func main() {
var s1 student
s1.name = "mayuan"
s1.age = 26
fmt.Println("s1 = ", s1)
}
指针操作
package main
import (
"fmt"
)
type student struct {
id int
name string
age int
addr string
}
func main() {
//指针指向合法操作后,才操作成员
var s student
var p1 *student
p1 = &s
//使用 p1.id和(*p1).id相同
p1.name = "mayuan"
(*p1).addr = "tianjin"
p1.age = 26
fmt.Println("s = ", s)
//使用new 得到一个指针
p2 := new(student)
p2.addr = "haha"
fmt.Println("*p2 = ", *p2)
}
参数为值传递
package main
import "fmt"
type student struct {
age int
username string
}
func changeStu(stu student){
stu.username = "LiLi"
}
func main() {
lili := student{24,"lili"}
changeStu(lili)
fmt.Println(lili)
}
//*********输出***********
{24 lili}
Tags 标签(可以在元素后面添加 `标签1 标签2 标签3` 来定义元素的属性)
type student struct {
age int `json:"age" xml:"age"`
username string
}