两个不依赖 core 和 std 库的简单 Rust 程序

注意:编译本文代码需要最新 Rust Nightly 编译器。

1. Hello, world!

#![feature(intrinsics, lang_items, no_core)]
#![no_core]
#![no_main]

#[lang = "copy"]
trait Copy {}

#[lang = "sized"]
trait Sized {}

#[cfg_attr(unix, link(name = "c"))]
extern "C" {
    fn puts(s: *const u8) -> i32;
}

extern "rust-intrinsic" {
    fn transmute<T, U>(x: T) -> U;
}

#[cfg(all(windows, target_env = "gnu"))]
pub mod eh_frame_registry
{
    #[no_mangle]
    pub extern "C" fn rust_eh_register_frames() {}

    #[no_mangle]
    pub extern "C" fn rust_eh_unregister_frames() {}
}

#[no_mangle]
pub extern "C" fn main() -> i32 {
    unsafe {
        puts(transmute::<_, (_, usize)>("Hello, world!\0").0);
    }

    0
}

Rust Playground: https://play.rust-lang.org/?gist=2ea96360b430e9e65516f680cc2b2f8f&version=nightly&backtrace=0
Gist: https://gist.github.com/2ea96360b430e9e65516f680cc2b2f8f

2. 按照“[序号]\t”参数””的格式逐行输出程序名和命令行参数

#![feature(intrinsics, lang_items, no_core)]
#![no_core]
#![no_main]

#[lang = "copy"]
trait Copy {}

#[lang = "ord"]
trait PartialOrd {
    fn lt(&self, other: &Rhs) -> bool;
}

#[lang = "sized"]
trait Sized {}

impl PartialOrd for i32 {
    #[inline]
    fn lt(&self, other: &Self) -> bool {
        *self < *other
    }
}

#[cfg_attr(unix, link(name = "c"))]
extern "C" {
    #[cfg_attr(all(windows, target_env = "gnu"), link_name = "__mingw_printf")]
    fn printf(f: *const u8, ...) -> i32;
}

extern "rust-intrinsic" {
    fn add_with_overflow<T>(x: T, y: T) -> (T, bool);
    fn offset<T>(dst: *const T, offset: isize) -> *const T;
    fn transmute<T, U>(x: T) -> U;
}

#[cfg(all(windows, target_env = "gnu"))]
pub mod eh_frame_registry {
    #[no_mangle]
    pub extern "C" fn rust_eh_register_frames() {}

    #[no_mangle]
    pub extern "C" fn rust_eh_unregister_frames() {}
}

#[no_mangle]
pub extern "C" fn main(argc: i32, argv: *const *const u8) -> i32 {
    let mut i = 0i32;

    unsafe {
        while i < argc {
            printf(transmute::<_, (_, usize)>("[%d]\t\"%s\"\n\0").0,
                   i,
                   *offset(argv, i as _));
            i = add_with_overflow(i, 1).0;
        }
    }

    0
}

Rust Playground: https://play.rust-lang.org/?gist=d3f790523c17bff89b5a979809c9cd96&version=nightly&backtrace=0
Gist: https://gist.github.com/d3f790523c17bff89b5a979809c9cd96

你可能感兴趣的:(两个不依赖 core 和 std 库的简单 Rust 程序)