小编Gig*_*him的帖子

如何将Rust字符串转换为UTF-16?

编者注:此代码示例来自1.0之前的Rust版本,并且不是有效的Rust 1.0代码,但是答案仍然包含有价值的信息。

我想将字符串文字传递给Windows API。许多Windows函数使用UTF-16作为字符串编码,而Rust的本机字符串是UTF-8。

我知道Rust有utf16_units()来生成UTF-16字符迭代器,但是我不知道如何使用该函数来生成UTF-16字符串(最后一个字符为零)。

我正在生成这样的UTF-16字符串,但我确信有更好的方法来生成它:

extern "system" {
    pub fn MessageBoxW(hWnd: int, lpText: *const u16, lpCaption: *const u16, uType: uint) -> int;
}

pub fn main() {
    let s1 = [
        'H' as u16, 'e' as u16, 'l' as u16, 'l' as u16, 'o' as u16, 0 as u16,
    ];
    unsafe {
        MessageBoxW(0, s1.as_ptr(), 0 as *const u16, 0);
    }
}
Run Code Online (Sandbox Code Playgroud)

string utf-16 rust

7
推荐指数
2
解决办法
4218
查看次数

为什么Rust没有deref && String to && str?

这段代码:

fn main() {
    let s = "hello".to_string();
    let keywords = vec!["hello", "bye"];

    // if keywords.contains(&s.as_str())
    if keywords.contains(&&s)
    // ~> expected &&str, found &collections::string::String
    {
        println!("exists");
    }
}
Run Code Online (Sandbox Code Playgroud)

通常,当函数期望&str类型时,你可以给一个String

let s = "abc".to_string();
foo(&s); // ok,
Run Code Online (Sandbox Code Playgroud)

但是&&s不DEREF来&&str,我认为这是不一致的.

string rust

6
推荐指数
0
解决办法
402
查看次数

VacantEntry未在名为set的范围内实现任何方法

这段代码:

use std::collections::hash_map::Entry::{Occupied, Vacant};
use std::collections::HashMap;

fn main() {
    let mut vars = HashMap::<i32, f64>::new();
    let key = 10;
    let val = match vars.entry(key) {
        Vacant(entry) => entry.set(0.0),
        Occupied(entry) => entry.into_mut(),
    };

    *val += 3.4;
    println!("{}", val);
}
Run Code Online (Sandbox Code Playgroud)

给出了这个错误:

error[E0599]: no method named `set` found for type `std::collections::hash_map::VacantEntry<'_, i32, f64>` in the current scope
 --> src/main.rs:8:32
  |
8 |         Vacant(entry) => entry.set(0.0),
  |                                ^^^
Run Code Online (Sandbox Code Playgroud)

hashmap rust

3
推荐指数
1
解决办法
1843
查看次数

标签 统计

rust ×3

string ×2

hashmap ×1

utf-16 ×1