Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

map

map中元素为结构体,不能直接修改,因为map元素无法取地址;

type Student struct {
	name string
}

修改map中struct元素的值,错误示例:

func TestMap(t *testing.T)  {
	m := map[string]Student11{"people": {"zhoujielun"}}
  //编译错误 Cannot assign to m["people"].name
	m["people"].name = "wuyanzu"
}

解决办法:

func TestMap(t *testing.T)  {
  //Student => *Student
	m := map[string]*Student{"people": {"zhoujielun"}}
  //编译错误 Cannot assign to m["people"].name
	m["people"].name = "wuyanzu"
}