// 先声明map var m1 map[string]string // 再使用make函数创建一个非nil的map,nil map不能赋值 m1 = make(map[string]string) // 最后给已声明的map赋值 m1["a"] = "aa" m1["b"] = "bb" // 直接创建 m2 := make(map[string]string) // 然后赋值 m2["a"] = "aa" m2["b"] = "bb" // 初始化 + 赋值一体化 m3 := map[string]string{ "a": "aa", "b": "bb", } // ========================================== // 查找键值是否存在 if v, ok := m1["a"]; ok { fmt.Println(v) } else { fmt.Println("Key Not Found") } // 遍历map for k, v := range m1 { fmt.Println(k, v) }
```go
package user
import (
"strconv"
)
type User struct {
name string
age int
sex string
phone string
}
func (s *User) SetName(name string) {
s.name = name
}
func (s *User) GetName() string {
return s.name
}
func (s *User) SetAge(age int) {
s.age = age
}
func (s *User) GetAge() int {
return s.age
}
func (s *User) String() string {
return "name is " + s.name + ",age is " + strconv.Itoa(s.age) + " ,sex=" + s.sex + " ,phone=" + s.phone
}
func (s *User) SetSex(sex string) {
s.sex = sex
}
func (s *User) GetSex() string {
return s.sex
}
func (s *User) SetPhone(phone string) {
s.phone = phone
}
func (s *User) GetPhone() string {
return s.phone
}
func (User) Print() string {
return "print"
}
```
#4