[英]how to copy contents of one slice to another slice in go
I'm doing below exercise in go. 我在做下面的运动。
Create a slice with four elements. 创建一个包含四个元素的切片。 Create a new slice and copy the third and fourth elements only into it.
创建一个新的切片,并将第三个和第四个元素仅复制到其中。
I have return the below program 我已经返回了以下程序
package main
import "fmt"
func main() {
var elements = make([]string, 4)
elements[0] = "1"
elements[1] = "2"
elements[2] = "3"
elements[3] = "4"
fmt.Println(elements)
var newElements = make([]string, 2)
newElements = append(elements[:0], elements[:2]...)
fmt.Println(newElements)
}
output of my program is. 我程序的输出是。 But I want the newElements slice to be [3 4]-
但我希望newElements切片为[3 4]-
[1 2 3 4]
[1 2]
What is wrong in my program. 我的程序出了什么问题。
Use the built-in copy function to copy elements from one slice to another. 使用内置的复制功能将元素从一个切片复制到另一个切片。
var newElements = make([]string, 2)
copy(newElements, elements[2:])
Run it on the playground 在操场上跑
You can use append to create the slice and copy the elements in a single statement, but the code is not as obvious as using copy. 您可以使用append创建切片并在单个语句中复制元素,但是代码并不像使用copy那样明显。
newElements := append([]string(nil), elements[2:4]...)
Problem is in the line newElements = append(elements[:0], elements[:2]...)
. 问题出在
newElements = append(elements[:0], elements[:2]...)
。 Here elements[:2]
means elements elements[0]
, elements[1]
. 这里
elements[:2]
表示元素elements[0]
, elements[1]
。 That's why your output is [1,2]
. 这就是为什么您的输出为
[1,2]
。 For third and fourth elements use this elements[2:4]
. 对于第三和第四元素,请使用此
elements[2:4]
。
package main
import "fmt"
func main() {
var elements = make([]string, 4)
elements[0] = "1"
elements[1] = "2"
elements[2] = "3"
elements[3] = "4"
fmt.Println(elements)
var newElements = make([]string, 2)
newElements = append(elements[:0], elements[2:4]...)
fmt.Println(newElements)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.