有没有类似于`append`的内置函数可以将切片的元素连接起来?

huangapple go评论64阅读模式
英文:

Is there a built-in function to concatenate element of a slice similar to append?

问题

我的目标是使用内置函数(如果存在)来连接元素。

当前的解决方案:

package main

import "fmt"

func main() {
	line1 := []string{"1 2", "1", "2"}
	line2 := []string{"sub2", "", "sub2"}
	line1[2] = line1[2] + "\n" + line2[2]
	fmt.Println(line1[2])
}

我的回答中只包含翻译好的部分,不包含其他内容。

英文:

My goal is to use the built-in function (if exist) to concatenate element.

The current solution:

package main

import "fmt"

func main() {

	line1 := []string{"1 2", "1", "2"}
	line2 := []string{"sub2", "", "sub2"}
	line1[2] = line1[2] + "\n" + line2[2]
	fmt.Println(line1[2])

}

答案1

得分: 1

如果你想要连接相同索引位置的元素。

package main

import "fmt"

func main() {

    line1 := []string{"1 2", "1", "2"}
    line2 := []string{"sub2", "", "sub2"}
    line3 := make([]string, len(line1))
    for i := 0; i < len(line1); i++ {
        line3[i] = line1[i] + line2[i]
    }
    fmt.Println(line3)
}

如果你想要连接相同索引位置的元素,可以使用上述代码。

英文:

if you are trying to concat the elements of same index.

package main

import &quot;fmt&quot;

func main() {

	line1 := []string{&quot;1 2&quot;, &quot;1&quot;, &quot;2&quot;}
	line2 := []string{&quot;sub2&quot;, &quot;&quot;, &quot;sub2&quot;}
	line3 := make([]string, len(line1))
	for i := 0; i &lt; len(line1); i++ {
		line3[i] = line1[i] + line2[i]
	}
	fmt.Println(line3)
}

huangapple
  • 本文由 发表于 2022年8月29日 14:41:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/73524982.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定