Skip to content

类型转换

本页展示了将基本类型之间进行转换以及从复合类型获取它们的示例。

Int ↔ String

如何将 String 转换为 Int

typescript
extends fun toInt(self: String): Int {
    let string: Slice = self.asSlice();
    let acc: Int = 0;
    
    while (!string.empty()) {
        let char: Int = string.loadUint(8);
        acc = (acc * 10) + (char - 48);
    }
    
    return acc;
}

fun runMe() {
    let string: String = "26052021";
    dump(string.toInt());
}

如何将 Int 转换为 String

typescript
let number: Int = 261119911;

let numberString: String = number.toString();
let floatString: String = number.toFloatString(3);
let coinsString: String = number.toCoinsString();

dump(numberString); // "261119911"
dump(floatString);  // "261119.911"
dump(coinsString);  // "0.261119911"

有用链接:

Struct or Message ↔ Cell or Slice

如何将任意 Struct 或 Message 转换为 Cell 或 Slice

typescript
struct Profit {
    big: String?;
    dict: map<Int, Int as uint64>;
    energy: Int;
}

message(0x45) Nice {
    maybeStr: String?;
}

fun convert() {
    let st = Profit{
        big: null,
        dict: null,
        energy: 42,
    };
    let msg = Nice{ maybeStr: "Message of the day!" };

    st.toCell();
    msg.toCell();

    st.toCell().asSlice();
    msg.toCell().asSlice();
}

有用链接:

如何将 Cell 或 Slice 转换为任意 Struct 或 Message

typescript
struct Profit {
    big: String?;
    dict: map<Int, Int as uint64>;
    energy: Int;
}

message(0x45) Nice {
    maybeStr: String?;
}

fun convert() {
    let stCell = Profit{
        big: null,
        dict: null,
        energy: 42,
    }.toCell();
    let msgCell = Nice{ maybeStr: "Message of the day!" }.toCell();

    Profit.fromCell(stCell);
    Nice.fromCell(msgCell);

    Profit.fromSlice(stCell.asSlice());
    Nice.fromSlice(msgCell.asSlice());
}

有用链接: