< 返回版块

Effective Rust 50坑

damody 发表于

第一坑 數字自動轉型

  • for loop 一定要顯示宣告 https://play.rust-lang.org/?gist=33831e35c8fad7cac6ebb151c8690c7f&version=stable

你的for loop可能會因為自動推導,導成不預期的值

// 這邊的4096被u8整除變0
for x in 0..4096 {
    // ...
}

建議所有loop的型別一定要顯示宣告

for x in 0..4096 as u32 {
    // ...
}
for x in 0..4096u32 {
    // ...
}

第二坑 match 比 index array 慢

https://github.com/luizirber/nthash/pull/2 這邊有人討論說 match竟然比lookup慢了快80% !!!

因此這篇作者想了解為什麼 https://kevinlynagh.com/notes/match-vs-lookup/

fn match4(x: u8) -> u64 {
    match x {
        b'A' => 1,
        b'B' => 2,
        b'C' => 3,
        b'D' => 4,
        _ => 0,
    }
}
use lazy_static::lazy_static;
lazy_static! {
    static ref LOOKUP4: [u64; 256] = {
        let mut l = [0; 256];

        l[b'A' as usize] = 1;
        l[b'B' as usize] = 2;
        l[b'C' as usize] = 3;
        l[b'D' as usize] = 4;

        l
    };
}

fn lookup4(x: u8) -> u64 {
    LOOKUP4[x as usize]
}

评论区

XG.Ley 2019-01-30T12:35:07.422643

第一个“坑”编译器早已给出警告了:

warning: literal out of range for u8
 --> src/main.rs:4:17
  |
4 |     for x in 0..4096 {
  |                 ^^^^
  |
作者 damody 2019-02-02T03:14:23.656289

在2018警告亂噴 各種命名提示警告 我通常會把警告關掉

cxq 2019-02-05T08:57:19.248020

还有呢?

1 共 3 评论, 共 1 页