我有一个字符串元素数组,我想将值复制到一个新数组。
我该怎么做?
答案 0 :(得分:0)
您可以声明一个相同类型的新数组,并通过赋值来复制它们。
// Declare a string array of five elements.
var array1 [5]string
// Declare a second string array of five elements.
// Initialise the array with values.
array2 := [5]string{"A", "B", "C", "D", "E"}
// Copy the values from array2 into array1.
array1 = array2
请注意,您无法分配不同大小的数组:
// Declare a string array of four elements.
var array1 [4]string
// Declare a second string array of five elements.
// Initialize the array with colors.
array2 := [5]string{"A", "B", "C", "D", "E"}
// Copy the values from array2 into array1.
array1 = array2
Compiler Error:
cannot use array2 (type [5]string) as type [4]string in assignment