gpt4 book ai didi

rust - 是一个字符串数组,例如[字符串; 3] 存储在栈上还是堆上?

转载 作者:行者123 更新时间:2023-11-29 07:55:50 24 4
gpt4 key购买 nike

Rust 书中规定:

Another property that makes the stack fast is that all data on the stack must take up a known, fixed size.

它还说 String 存储在堆上,因为大小未知并且可以变异。

“复合”数据结构(例如包含 String 的数组)存储在哪里?数组的大小是固定的,但数组的组成部分的大小可以改变。

let array: [String; 3] = ["A","B","C"];

存储这种“复合”数据类型的规则是什么?

最佳答案

两者


术语的一点:在讨论一个类型的内存布局时,不应该谈论stack vs heap,而是inline vs offline1:

  • 内联 意味着数据就在这里,
  • 离线 意味着数据在指针后面可用(无论指针指向何处)。

一个简单的例子,整数存储在行内:

//  i32
+---+
| 3 |
+---+

一个典型的struct Point { x: i32, y: i32 }也内联存储:

//  Point
+---+---+
| x | y |
+---+---+

A String ,通常表示为 struct String { data: *mut u8, len: usize, cap: usize }在线和离线存储:

//   String
+-------+-------+-------+
| data | len | cap |
+-------+-------+-------+
|
\
+-------------+
|Hello, World!|
+-------------+

内联部分是 3 个指针的存储空间,离线部分是堆分配的记录,其中包含字符串 "Hello, World!" 的内容。在这里。

但是,内联并不总是意味着堆栈Box<Point> :

//  Box<Point>
+-------+
| data |
+-------+
|
\
+---+---+
| x | y |
+---+---+

存储其 Point (内联存储其数据成员)在堆上!

同样,离线并不总是意味着:

fn main() {
let i = 3;
let r = &i;
}

在这里,r是一个引用(指针),指向i , 和 i在堆栈上!

1 是的,这是我编造的,我们将不胜感激。


所以,回到问题:

It also says that String is stored on the heap as the size is not known and can mutate.

这是一个近似值,如上所述 String有一些内联数据(指针、长度和容量)和堆上的一些数据(字符串内容)。

Where are "composite" data structures such as arrays containing String stored? The array is fixed in size however the components of the array can change in size.

let array: [String; 3] = ["A","B","C"];

它同时存储在栈和堆上:

//  [String; 3]
+-------+-------+-------+-------+-------+-------+-------+-------+-------+
| data | len | cap | data | len | cap | data | len | cap |
+-------+-------+-------+-------+-------+-------+-------+-------+-------+
| | |
\ \ \
+-+ +-+ +-+
|A| |B| |C|
+-+ +-+ +-+

这是 9 个指针的内联数据(在堆栈上)和堆上的 3 个独立分配。

What is the rule for where such "composite" data types are stored?

数据成员总是内联,指针和引用可能指向离线数据,这些数据可能在堆上、堆栈上等...

关于rust - 是一个字符串数组,例如[字符串; 3] 存储在栈上还是堆上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47179667/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com