猿问

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

我想初始化一个二维数组,其中内部数组的每个成员都包含一个 1000 x 的字符串。就像是:

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

但是所有的谷歌搜索都是徒劳的。在 C++ 中,我可以实现类似的事情:

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

在 Ruby 中是这样的:

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

想要在 go 中获得类似的结果,但我找不到任何文档来填充字符串并初始化 2D 数组。另请注意,我想为数组的每个成员生成字符串,而不是使用可用的字符串。

PS:我也在 Rust 中寻找类似的东西


温温酱
浏览 379回答 3
3回答

海绵宝宝撒

在 Rust 中,这取决于您要将这些值用于什么目的。我喜欢这个创建重复字符串的答案。“行”取决于您是否需要在 rust 中明确表示的引用或复制语义。borrows向量是一堆借来的字符串,它们引用x_s. 向量是原始字符串的copies一堆内存副本。x_suse std::iter;fn main() {&nbsp; &nbsp; let num_rows = 1000;&nbsp; &nbsp; let num_cols = 1000;&nbsp;&nbsp; &nbsp; let x_s : String = iter::repeat('x').take(num_cols).collect();&nbsp; &nbsp; // pick one of the below&nbsp; &nbsp; let borrows : Vec<&str> = vec![&*x_s ; num_rows];&nbsp; &nbsp; let copies : Vec<String> = vec![x_s.clone() ; num_rows];}最后一行中的调用clone是因为vec宏将发送的值移动到其中。在. vec_ num_rows_ copies请注意,clone在大多数用例中这可能不是必需的,因为您通常不会borrows同时copies在同一范围内。作为警告,我对生锈还很陌生,但相信这是一个不错的答案。我很高兴接受更正。

莫回无

你可以使用切片。这可能不是最短的解决方案,但它对我有用。package mainimport (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "strings")func main() {&nbsp; &nbsp; xs := strings.Repeat("x", 1000)&nbsp; &nbsp; num_rows := 5&nbsp; &nbsp; num_cols := 5&nbsp; &nbsp; data := make([][]string, num_rows)&nbsp; &nbsp; for y := 0; y < num_rows; y++ {&nbsp; &nbsp; &nbsp; &nbsp; data[y] = make([]string, num_cols)&nbsp; &nbsp; &nbsp; &nbsp; for x := 0; x < num_cols; x++ {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; data[y][x] = xs&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; fmt.Printf("%T", data)&nbsp; &nbsp; fmt.Print(data)}

胡子哥哥

一个非常简单的 rust 在线示例:fn main() {&nbsp; &nbsp; let data: Vec<String> = (0..1000).map(|n| (0..n).map(|_| 'x').collect()).collect();&nbsp; &nbsp; println!("{:?}", data);}
随时随地看视频慕课网APP

相关分类

Go
我要回答