Last active
August 29, 2015 14:00
-
-
Save defp/11027253 to your computer and use it in GitHub Desktop.
不对slice类型的参数进行append
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
) | |
func operatSlice(s []int, num int) []int { | |
for i := 0; i < num; i++ { | |
s = append(s, 4) | |
} | |
s[0] = num | |
return s | |
} | |
func main() { | |
s := make([]int, 0, 3) | |
s = append(s, 1) | |
fmt.Printf("s=%+v\n", s) // s=[1] | |
fmt.Println("==========") | |
s1 := operatSlice(s, 2) | |
fmt.Printf("s=%+v\n", s) // s=[2] | |
fmt.Printf("s1=%+v\n", s1) // s=[2 4 4] | |
fmt.Println("==========") | |
s2 := operatSlice(s, 3) | |
fmt.Printf("s=%+v\n", s) // s=[] | |
fmt.Printf("s1=%+v\n", s1) | |
fmt.Printf("s2=%+v\n", s2) | |
} | |
/* | |
$ go run b.go | |
s=[1] | |
========== | |
s=[2] | |
s1=[2 4 4] | |
========== | |
s=[2] | |
s1=[2 4 4] | |
s2=[3 4 4 4] | |
*/ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
) | |
func main() { | |
arr := []int{1, 2, 3, 4, 5} | |
slice := arr[1:2] | |
slice = append(slice, 6, 7, 8) | |
fmt.Println(slice) | |
fmt.Println(arr) | |
fmt.Println("=========") | |
arr1 := []int{1, 2, 3, 4, 5} | |
slice1 := arr[1:2] | |
slice1 = append(slice1, 6, 7, 8, 9) | |
fmt.Println(slice1) | |
fmt.Println(arr1) | |
} | |
/* | |
output: | |
[2 6 7 8] | |
[1 2 6 7 8] | |
========= | |
[2 6 7 8 9] | |
[1 2 3 4 5] | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment