【问题标题】:How to copy a string array into another string array?如何将一个字符串数组复制到另一个字符串数组中?
【发布时间】:2015-08-22 04:13:12
【问题描述】:

我有一个字符串元素数组,我想将这些值复制到一个新数组中。

我该怎么做?

【问题讨论】:

  • 作业或copy.
  • 技术上assign。搜索引擎优化的人可能会通过搜索copy 找到此问答。

标签: arrays string go


【解决方案1】:

您可以声明一个相同类型的新数组,并通过分配它来复制值。

// 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

【讨论】:

  • 对,你可以复制但不能分配。
猜你喜欢
  • 1970-01-01
  • 2010-10-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-15
  • 1970-01-01
  • 1970-01-01
  • 2015-06-06
相关资源
最近更新 更多