GolangNote

Golang笔记

golang 实现slice append和prepend

Permalink

golang 实现slice append和prepend

Go: append
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package main

import (
	"fmt"
	"strings"
)

func main() {
	str := "a,b,c"
	mySlice := strings.Split(str, ",")
	mySlice = append(mySlice, "1")              // append
	mySlice = append([]string{"2"}, mySlice...) // prepend
	fmt.Println(mySlice)
	fmt.Println(strings.Join(mySlice, ","))
}

没有内置的函数实现 prepend 不过 go 的实现方式也比较优雅:

Go: prepend
1
mySlice = append([]string{"2"}, mySlice...)

本文网址: https://golangnote.com/topic/131.html 转摘请注明来源

Related articles

Golang 实现 10 进制转 N 进制

给定一个不没有重复字符的字符串,如 `[0-9,a-z]`,把一个 10 进制数字转为,该字符集的字符串。应用场合如汽车牌、顺序计数。...

Golang phantomjs 动态代理实现

phantomjs 是个很优秀的软件,虽然现在被chrome headless 抢了风头,但在某些特定场合,使用phantomjs 还是很方便,这里是介绍使用Go 实现动态代理。...

Golang实现简单的Socks5代理

Socks5 代理较 `http/https` 代理有较好的性能,下面是借鉴某个著名开源软件的 local 实现的简单代理。...

Write a Comment to "golang 实现slice append和prepend"

Submit Comment Login
Based on Golang + fastHTTP + sdb | go1.20 Processed in 0ms