如何将一个切片的内容复制到另一个切片中 [英] how to copy contents of one slice to another slice in go

查看:120
本文介绍了如何将一个切片的内容复制到另一个切片中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做下面的运动.

创建一个包含四个元素的切片.创建一个新的切片并复制第三个 和第四个元素.

Create a slice with four elements. Create a new slice and copy the third and fourth elements only into it.

我已经退回了以下程序

    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)
    }

我程序的输出是.但我希望newElements切片为[3 4]-

output of my program is. But I want the newElements slice to be [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:])

在操场上运行

您可以使用append创建切片并在单个语句中复制元素,但是代码并不像使用copy那样明显.

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.

newElements := append([]string(nil), elements[2:4]...)

在操场上运行.

这篇关于如何将一个切片的内容复制到另一个切片中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆