相关疑难解决方法(0)

Rust的`String`和`str`之间有什么区别?

为什么Rust有StringstrString和之间有什么区别str?什么时候使用String而不是str反之亦然?其中一个被弃用了吗?

string rust

341
推荐指数
13
解决办法
4万
查看次数

如何构建Rc <str>或Rc <[T]>?

我想创建一个Rc<str>因为我想减少间接跟随访问Rc<String>需求的2个指针.我需要使用一个,Rc因为我真的拥有共享权.我详细介绍了我在字符串类型中遇到的更具体问题.

Rc 有一个?Sized约束:

pub struct Rc<T: ?Sized> { /* fields omitted */ }
Run Code Online (Sandbox Code Playgroud)

我还听说Rust 1.2将提供适当的支持来存储未经过类型化的类型Rc,但我不确定它与1.1的区别.

str案例为例,我的天真尝试(也就是从a构建String)也失败了:

use std::rc::Rc;

fn main() {
    let a: &str = "test";
    let b: Rc<str> = Rc::new(*a);
    println!("{}", b);
}
Run Code Online (Sandbox Code Playgroud)
error[E0277]: the trait bound `str: std::marker::Sized` is not satisfied
 --> src/main.rs:5:22
  |
5 |     let b: Rc<str> = Rc::new(*a);
  |                      ^^^^^^^ `str` does not have …
Run Code Online (Sandbox Code Playgroud)

rust

15
推荐指数
2
解决办法
1258
查看次数

在 Rust 中,你能拥有一个字符串字面量吗?

根据The Rust 的书

Rust 中的每个值都有一个变量,称为其所有者。一次只能有一个所有者。当所有者超出范围时,该值将被删除。

根据rust-lang.org

静态项目不会在程序结束时调用 drop。

在阅读了这篇 SO post并给出了下面的代码后,我明白这foo是一个值,其变量y相当于&y因为“字符串文字是字符串切片”,被称为它的owner. 那是对的吗?还是静态项目没有所有者?

let x = String::from("foo");  // heap allocated, mutable, owned
let y = "foo" // statically allocated to rust executable, immutable
Run Code Online (Sandbox Code Playgroud)

我想知道,因为与拥有的不同String,字符串文字没有移动,大概是因为它们存储在.rodata可执行文件中

fn main() {
  let s1 = "foo"; // as opposed to String::from("foo")
  let s2 = s1; // not moved
  let s3 = s2; // no …
Run Code Online (Sandbox Code Playgroud)

string reference string-literals ownership rust

9
推荐指数
1
解决办法
1764
查看次数

什么"`str`没有在编译时知道的常量大小"是什么意思,什么是最简单的修复方法?

我正在尝试操作从函数参数派生的字符串,然后返回该操作的结果:

fn main() {
    let a: [u8; 3] = [0, 1, 2]; 
    for i in a.iter() {
        println!("{}", choose("abc", *i));
    }
}

fn choose(s: &str, pad: u8) -> String {
    let c = match pad {
        0 => ["000000000000000", s].join("")[s.len()..],
        1 => [s, "000000000000000"].join("")[..16],
        _ => ["00", s, "0000000000000"].join("")[..16],
    };
    c.to_string()
}
Run Code Online (Sandbox Code Playgroud)

在构建时,我收到此错误:

error[E0277]: the trait bound `str: std::marker::Sized` is not satisfied
 --> src\main.rs:9:9
  |
9 |     let c = match pad {
  |         ^ `str` does not have a …
Run Code Online (Sandbox Code Playgroud)

string pointers rust

7
推荐指数
1
解决办法
4242
查看次数

标签 统计

rust ×4

string ×3

ownership ×1

pointers ×1

reference ×1

string-literals ×1