duanfeng3879 2016-06-02 11:21
浏览 217

在GoLang和Rust中初始化字符串数组

I want to initialize a 2D array in which each member of inner array holds a string of 1000 x's. Something like:

var data = [num_rows][num_cols]string("x....x(upto 1000)")

But all google searches have been futile. In C++ I can achieve similar thing like this:

vector<vector<string>> data(num_rows, vector<string>(num_cols, string("x",1000)));

And in Ruby something like this:

Array.new(num_rows) { Array.new(num_cols) { "x"*1000 } }

Want to achieve similar result in go but I am unable to find any documentation to fill a string and initialize a 2D array. Also note that I want to generate the string for each member of array rather than using an available string.

PS : I am also looking for something similar in Rust

  • 写回答

3条回答 默认 最新

  • drphfy1198 2016-06-02 11:41
    关注

    you could use slices. this may not be the shortest solution, but it works for me.

    package main
    
    import (
        "fmt"
        "strings"
    )
    
    func main() {
        xs := strings.Repeat("x", 1000)
    
        num_rows := 5
        num_cols := 5
    
        data := make([][]string, num_rows)
        for y := 0; y < num_rows; y++ {
            data[y] = make([]string, num_cols)
            for x := 0; x < num_cols; x++ {
                data[y][x] = xs
            }
        }
    
        fmt.Printf("%T", data)
        fmt.Print(data)
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败