Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use the append () and copy () functions of Go language

Shulou Source: shulou.com Published: 2022-06-01 02:26:53 09月21日 Update

In this article Xiaobian for you to introduce in detail the "Go language append () and copy () function how to use", detailed content, clear steps, details handled properly, I hope that this "Go language append () and copy () function how to use" the article can help you solve doubts, following the editor's ideas slowly in-depth, together to learn new knowledge.

Append () and copy () functions

If we want to increase the capacity of the slice, we must create a new and larger slice and copy the contents of the original slice.

The following code describes the copy method from the copy slice and the append method to append new elements to the slice.

Example

Package main

Import "fmt"

Func main () {

Var numbers [] int

PrintSlice (numbers)

/ * allow empty slices to be appended * /

Numbers = append (numbers, 0)

PrintSlice (numbers)

/ * add an element to the slice * /

Numbers = append (numbers, 1)

PrintSlice (numbers)

/ * add multiple elements at the same time * /

Numbers = append (numbers, 2pm 3pm 4)

PrintSlice (numbers)

/ * creating a slice numbers1 is twice the capacity of the previous slice * /

Numbers1: = make ([] int, len (numbers), (cap (numbers)) * 2)

/ * copy the contents of numbers to numbers1 * /

Copy (numbers1,numbers)

PrintSlice (numbers1)

}

Func printSlice (x [] int) {

Fmt.Printf ("len=%d cap=%d slice=%v\ n", len (x), cap (x), x)

}

The output of the above code execution is as follows:

Len=0 cap=0 slice= [] len=1 cap=1 slice= [0] len=2 cap=2 slice= [0 1] len=5 cap=6 slice= [0 12 3 4] len=5 cap=12 slice= [0 12 3 4] here, this article "how to use the append () and copy () functions of Go language" has been introduced. If you want to master the knowledge of this article, you still need to practice and use it yourself to understand it. If you want to know more about related articles, please pay attention to the industry information channel.

Tags: Function content language element copy article code capacity method appropriate at the same time multiple examples ideas new knowledge more steps knowledge knowledge points articles Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Docker Huawei OPPO Reno MariaDB Apple