在这段Golang代码中,我有一个名为developers的变量,它等于两个切片.我希望它们等于一个切片,如所需结果所示.

虽然我可以像这样把它们写在一张薄片上,但我想把它们分开写,作为一个整体打印,但要被视为像[[first developer second developer]...]这样的多个实体

Given result

[[first developer] [second developer] [first project second project] [third project forth project]]

Required result

[[first developer second developer] [first project second project] [third project forth project]]

Code

package main

import "fmt"

func main() {
    developers := [][]string{
        {"first developer"},
        {"second developer"},
    }
    var data [][]string
    for i := 0; i < 2; i++ {
        data = append(data, developers[i])
    }
    data = append(data, [][]string{
        {"first project", "second project"},
        {"third project", "forth project"},
    }...)
    fmt.Println(data)
}

推荐答案

它看起来首先您想要"展平"developers2D切片([][]string).为此,对其进行排列,并将其1D切片元素附加到1D切片([]string).然后使用这个1D切片作为最终data个2D切片的元素.

例如:

developers := [][]string{
    {"first developer"},
    {"second developer"},
}
var devs []string
for _, v := range developers {
    devs = append(devs, v...)
}

data := [][]string{
    devs,
    {"first project", "second project"},
    {"third project", "forth project"},
}
fmt.Println(data)

这将输出(在Go Playground上试用):

[[first developer second developer] [first project second project] [third project forth project]]

Go相关问答推荐

如何预编译Golang标准库?

Websocket服务器实现与x/net库trowing 403

Golang SDK for DynamoDB:ReturnValuesOnConditionCheckFailure在条件chcek失败发生时不返回条件的详细信息

如何确定泛型类型在运行时是否可比较?

有没有办法让sqlc生成可以使用pgxpool的代码

启动套接字服务器会干扰 gRPC/http 客户端服务器通信 Golang

Golang校验器包:重命名字段错误处理

带有前导零的整数参数被 flag.IntVar 解析为八进制

Golang 创建一个带有处理程序的模拟数据库并使用接口调用数据库

有没有办法计算枚举中定义的项目总数?

动态 SQL 集 Golang

每次有人进入我的网站时如何运行特定功能?

如何使用 math/big 对 bigInt 进行取模?

如果服务器在客户端的 gRPC 中不可用,则等待的方法

Terraform 自定义提供程序 - 数据源架构

如何在 Unmarshal 中使用泛型(转到 1.18)

退格字符在围棋操场中不起作用

行之间的模板交替设计

如何访问Go 1.18泛型 struct (structs)中的共享字段

如果在调用 http.Get(url) 时发生错误,我们是否需要关闭响应对象?