Golang中如何扩展字符串列表中的数组值

Golang中如何扩展字符串列表中的数组值 我有以下代码:

a[0] = "Hello"
a[1] = "World"
a[2] = "something"

vs.top = []string{"a[0]", "Cool stuff"}

我希望扩展为 vs.top = []string{“Hello”, “World”, “Something”, “Cool stuff”}

基本上,我通过读取一些数据来更新数组,并希望相应地更新 vs.top 谢谢

5 回复

太棒了,这个方法有效

vs.Rules = []string{strings.Join(append(a, "Cool stuff"), "")}

更多关于Golang中如何扩展字符串列表中的数组值的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


只需将其追加到切片中,即可返回一个包含新增值的新切片:

a[0] = "Hello"
a[1] = "World"
a[2] = "something"

vs.top = append(a, "Cool Stuff")

如果你想将它们合并成一个单独的字符串,必须使用 strings.Join(append(a, "Cool stuff"), " ") 来将这些字符串以空格分隔连接起来。

strings.Join(append(a, "Cool stuff"), " ")

@Sandertv 感谢,我想在字符串中使用它,但使用时出现了错误

vs.Rules = []string{append(a, "Cool stuff")}
go run f5gohello.go
# command-line-arguments
./f5gohello.go:184:32: cannot use append(a, "Cool stuff") (type []string) as type string in array or slice literal

在Go语言中,可以通过切片操作和append函数来扩展字符串列表。根据你的需求,需要将数组a中的元素和新的字符串元素合并到vs.top中。

以下是实现代码示例:

package main

import "fmt"

type VS struct {
    top []string
}

func main() {
    // 初始化数组a
    a := [3]string{"Hello", "World", "something"}
    
    // 初始化VS结构体
    vs := VS{}
    
    // 将数组a的所有元素和新的字符串合并到vs.top
    vs.top = append(a[:], "Cool stuff")
    
    fmt.Println(vs.top) // 输出: [Hello World something Cool stuff]
}

如果你需要更灵活地处理,比如只选择数组中的特定元素,可以这样做:

// 如果只需要数组a的前两个元素
vs.top = append(a[0:2], "Cool stuff")
fmt.Println(vs.top) // 输出: [Hello World Cool stuff]

// 如果需要数组a的所有元素加上多个新元素
vs.top = append(a[:], "Cool stuff", "Another item")
fmt.Println(vs.top) // 输出: [Hello World something Cool stuff Another item]

如果你的数组a是动态生成的,可以使用切片而不是数组:

a := []string{"Hello", "World", "something"}
vs.top = append(a, "Cool stuff")

这种方法利用了Go语言切片的灵活性,append函数会自动处理内存分配和容量扩展。

回到顶部