Rust从入门到高级(一):开发环境安装和hello world程序

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/xiangxianghehe/article/details/102761257

Rust Playground

如果只是写Demo测试,尝试下 Rust,可以无需安装Rust开发环境,直接在Rust Playground运行自己代码。

开发环境安装

强烈不建议各位童鞋使用Windows学习和开发Rust,如果预装了Win10系统,可以在Win10的Linux子系统进行配置,启用Win10的Linux子系统的教程见链接

如果你的主机不是windows系统,Mac OS, linux,Win10下Linux子系统或其他类Unix系统的话,都可以用

curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

这条命令来安装最新的Rust稳定版。

安装完毕后,在终端输入rustc --version即可查看当前的Rust版本:

root@host:~# rustc --version
rustc 1.38.0 (625451e37 2019-09-23)

crates.io换国内中科大/阿里云镜像源

Rust社区公开的第三方包都集中在crates.io网站上面,他们的文档被自动发布到doc.rs网站上。Rust提供了非常方便的包管理器cargo,它类似于Node.jsnpmPythonpip。但cargo不仅局限于包管理,还为Rust生态系统提供了标准的工作流。

在实际开发中,为了更快速下载第三方包,我们需要把crates.io换国内的镜像源。

换国内中科大源

执行以下命令即可:

tee $HOME/.cargo/config <<-'EOF'
[source.crates-io]
registry = "https://github.com/rust-lang/crates.io-index"
replace-with = 'ustc'
[source.ustc]
registry = "git://mirrors.ustc.edu.cn/crates.io-index"
EOF

换阿里云源

tee $HOME/.cargo/config <<-'EOF'
[source.crates-io]
replace-with = "rustcc"

[source.rustcc]
registry = "https://code.aliyun.com/rustcc/crates.io-index"
EOF

hello world程序

新建一个名为hello.rs的文件,写入以下内容:

fn main()
{
    println!("hello world!");
}

然后执行命令rustc hello.rs进行编译,会生成一个和代码文件同名的可执行文件hello,运行:

./hello

就能看到终端打印出hello world!

如果想指定编译后生成的可执行文件名,只需加参数-o,比如:

rustc hello.rs -o hello_test

会编译hello.rs并生成名为hello_test的可执行文件。

猜你喜欢

转载自blog.csdn.net/xiangxianghehe/article/details/102761257