go 使用注意: 变量名不能和包名相同,否则会 冲突了
目录结构
user/user.go
点击查看代码
package user
type User struct{
Username string
Sex string
Age int
AvatarUrl string
}
func NewUser(username string, sex string, age int,avatar string) *User{
// 如果对象比较大比较多,不用指针类型的话会产生拷贝,占用较多内存, 性能会很差,所以一般会选择指针类型
// 指针方式一,
/*user1 :=&User{
Username: username,
Sex:sex,
Age:age,
AvatarUrl:avatar,
}*/
// 指针方式二,
user := new(User)
user.Username = username
user.Sex = sex
user.Age = age
user.AvatarUrl = avatar
return user
}
user/user_test.go
点击查看代码
package main
import (
"../user"
"fmt"
)
func main(){
/*var user user.User // 变量名不能和包名相同,否则会 冲突了
user.age =18
fmt.Printf("user=%#v\n",user)*/
var user1 user.User // 变量名不能和包名相同,否则会 冲突了
user1.Age =18
fmt.Printf("user1=%#v\n",user1)
user2 := user.NewUser("user01","女",15,"xxx.jpg")
fmt.Printf("user2=%#v\n",user2)
}
输出:
user1=user.User{Username:"", Sex:"", Age:18, AvatarUrl:""}
user2=&user.User{Username:"user01", Sex:"女", Age:15, AvatarUrl:"xxx.jpg"}
写入自己的博客中才能记得长久