go go和c一样,所有的运算都应该在函数内进行
package main
import (
"fmt"
)
type User struct {
Username string
Sex string
Age int
int
string
}
type Address struct {
Province string
City string
}
type User1 struct {
Username string
Sex string
Address
}
type person struct {
name string
age int
}
var P person
var P2 = person{"annie",20}
/*go和c一样,所有的运算都应该在函数内进行,函数外进行的是语法错误.
函数体外初始化结构体就两个办法,要么一次性全部赋值,要么先声明(全局/局部)变量,
在某个函数内进行赋值,在函数体外进行结构体成员赋值相当于函数外面进行运算了.
var user User
user.Username = "user01"
user.Age =18
user.Sex ="男"
user.int =100
user.string = "hello"
*/
func main(){
var user User // 变量名不能和包名相同,否则会冲突了
user.Username = "user01"
user.Age = 18
user.Sex = "男"
user.int = 100
user.string = "hello"
fmt.Printf("user=%#v\n",user)
P.name="a"
P.age=10
fmt.Printf("001 The person's name is %s \n", P.name)
fmt.Printf("002 The person2's name is %s \n", P2.name)
var user1 User1
user1.Username = "user1"
user1.Sex = "男"
// 第一种方式
user1.Address = Address{
Province:"北京",
City:"北京",
}
// 第二种方式
/*user1.Province = "湖北"
user1.City = "黄冈"*/
fmt.Printf("user=%#v addr=%#v\n",user1,user1.Address)
fmt.Printf("user=%#v province=%v, city=%s\n",user1,user1.Province,user1.City)
}
输出:
user=main.User{Username:"user01", Sex:"男", Age:18, int:100, string:"hello"}
001 The person's name is a
002 The person2's name is annie
user=main.User1{Username:"user1", Sex:"男", Address:main.Address{Province:"北京", City:"北京"}} addr=main.Address{Province:"北京", City:"北京"}
user=main.User1{Username:"user1", Sex:"男", Address:main.Address{Province:"北京", City:"北京"}} province=北京, city=北京
写入自己的博客中才能记得长久