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
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)
}
In Rust, it depends on what you want to use these values for. I like this answer for creating the repeated string. The "rows" depend on if you want reference or copy semantics which is made explicit in rust. The borrows
vector is a bunch of borrowed strings that refer back to the memory owned by x_s
. The copies
vector is a bunch of in memory copies of the original x_s
string.
use std::iter;
fn main() {
let num_rows = 1000;
let num_cols = 1000;
let x_s : String = iter::repeat('x').take(num_cols).collect();
// pick one of the below
let borrows : Vec<&str> = vec![&*x_s ; num_rows];
let copies : Vec<String> = vec![x_s.clone() ; num_rows];
}
The call to clone
in the last line is because the vec
macro moves the value sent into it. The vec
macro will also clone this clone num_rows
times in the case of the copies
. Note that this clone
is probably not necessary in most use cases as you would not normally have borrows
and copies
in the same scope at the same time.
As a caveat, I am fairly new to rust but believe this to be a decent answer. I am happy to accept corrections.
A very simple on-line exemple in rust :
fn main() {
let data: Vec<String> = (0..1000).map(|n| (0..n).map(|_| 'x').collect()).collect();
println!("{:?}", data);
}