我有一个向量matrix_a,其中包含3个向量,并使用vec!宏进行初始化.
由于每个向量的容量应为3,Vec::with_capacity(dim)但只有最后一个向量的容量为3.其他向量的容量为0.
有人可以解释为什么会这样吗?
fn main() {
let dim = 3;
let matrix_a: Vec<Vec<i32>> = vec![Vec::with_capacity(dim); dim];
for vector in matrix_a{
println!("Capacity of vector: {}", vector.capacity());
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
Capacity of vector: 0
Capacity of vector: 0
Capacity of vector: 3
Run Code Online (Sandbox Code Playgroud) 是否可以只导出嵌入式结构实现的方法的子集?这是一种非常不同的方法来减少代码的复制和粘贴,还有一种更惯用的方法吗?
type A struct {
}
func (a *A) Hello() {
fmt.Println("Hello!")
}
func (a *A) World() {
fmt.Println("World!")
}
type B struct {
A
}
type C struct {
A
}
func main() {
b := B{}
c := C{}
// B should only export the Hello - function
b.Hello()
// C should export both Hello - and World - function
c.Hello()
c.World()
}
Run Code Online (Sandbox Code Playgroud)