Problems that need to be paid attention to when using for loop to modify the value of structure array in golang

Don't talk nonsense, go directly to the code:

	type a1 struct {
		key1 string
		key2 string
		key3 string
	}
	testData := []a1{
		a1{"1","2", "3"},
		a1{"4","5", "6"},
	}

The above code defines a structure and declares an array.

The value of the structure in the array can be modified by using the loop variable:

	for i := 0; i < len(testData); i++ {
		testData[i].key3 = "999"
	}
	fmt.Printf("%v", testData)

Output: [{1 2 999} {4 5 999}]

The subscript value obtained by range is used, and then the array item referenced by subscript can also be directly modified:

	for idx, _ := range testData {
		testData[idx].key3 = "999"
	}
	fmt.Printf("%v", testData)

Output: [{1 2 999} {4 5 999}]

Using range to get an array item cannot modify the value of the structure in the array:

	for _, item := range testData {
		item.key3 = "999"
	}
	fmt.Printf("%v", testData)

Output: [{1 2 3} {4 5 6}]

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325364769&siteId=291194637