rust

Why does a File need to be mutable to call Read::read_to_string?

*爱你&永不变心* 提交于 2020-08-06 07:50:28
问题 Here's a line from the 2nd edition Rust tutorial: let mut f = File::open(filename).expect("file not found"); I'm of the assumption that the file descriptor is a wrapper around a number that basically doesn't change and is read-only. The compiler complains that the file cannot be borrowed mutably, and I'm assuming it's because the method read_to_string takes the instance as the self argument as mutable, but the question is "why" ? What is ever going to change about the file descriptor? Is it

Cast vector of i8 to vector of u8 in Rust? [duplicate]

℡╲_俬逩灬. 提交于 2020-08-06 07:36:05
问题 This question already has answers here : How do I convert a Vec<T> to a Vec<U> without copying the vector? (2 answers) Closed 7 months ago . Is there a better way to cast Vec<i8> to Vec<u8> in Rust except for these two? creating a copy by mapping and casting every entry using std::transmute The (1) is slow, the (2) is "transmute should be the absolute last resort" according to the docs. A bit of background maybe: I'm getting a Vec<i8> from the unsafe gl::GetShaderInfoLog() call and want to

Type casting for Option type

北慕城南 提交于 2020-08-06 05:33:57
问题 I'm newbie in Rust from Python. I believe it's a basic question, but I am too new to find the answer by keywords like Type Casting Option . In Python, to make the type checker know return type is not Optional[int] + int , we can address assert logic to enforce the type checker know x will never be None after line assert . from typing import Optional def add_one(x: Optional[int] = None) -> int: if x is None: x = 0 assert x is not None return x + 1 if __name__ == '__main__': add_one(0) # 1 add

一个茴字有三种写法——吐槽C#9.0的Records

喜欢而已 提交于 2020-08-05 21:13:34
最近是微软开了Build 2020大会,由于疫情原因,改成了在线举行,Build大会上,C#公布9.0版本。 我个人对于C#的更新向来都是喜闻乐见,乐于接受的,对于博客园上某些人天天嘲讽C#只会增加语法糖的人,我向来对他们不屑一顾,认为他们是井底之蛙。 因此我仔细看了微软发的文章 Welcome to C# 9.0 ,准备好好观摩和学习。但当我看到Records语法时,我就隐隐感觉C#这样玩语法糖要翻车了。 后来看到知乎上的问题 如何评价即将发布的 C# 9.0? ,我稍加思索,愈发觉得Records语法完全是大型翻车现场,因此整理出来我认为的Records的翻车点(兼吐槽)。 首先看官方给出的Records样例 public data class Person { public string FirstName { get; init; } public string LastName { get; init; } } 第一个吐槽点: data class 声明有必要吗?如果要多加一个 data 关键字,直接用 record 不好吗,如果不加关键字,为什么不用 readonly class 啊。 public record Person {} public readonly class Person {} 第二个吐槽点,官方给出上面的等价定义 public data class

自从尝了 Rust,Java 突然不香了

落爺英雄遲暮 提交于 2020-08-05 12:27:10
Rust 是软件行业中相对而言比较新的一门编程语言,如果从语法上来比较,该语言与 C++ 其实非常类似,但从另一方面而言,Rust 能更高效地提供许多功能来保证性能和安全。而且,Rust 还能在无需使用传统的垃圾收集系统的情况下保证内存的安全性。 Rust 语言原本是 Mozilla 员工 Graydon Hoare 私人的项目,Graydon Hoare 当时是 Mozilla 研究部门的一位经验丰富的 IT 科学家。2009 年,Mozilla 开始赞助这个计划,并且在 2010 年首次揭露了它的存在。 随着越来越多设计者的加入,他们为该编程语言打造了浏览器引擎,并设计了 Rust 编译器。Rust 编译器是一款免费和开源的编程软件,受 MIT 许可证和 Apache 许可证保护。自 2016 年起,由于许多开发人员开始选择 Rust 而不是 Java 来进行栈溢出(Stack overflow)开发,Rust 语言开始成为人们关注的焦点。 Rust 官网链接: https://www.rust-lang.org/ 为什么 Rust 受到许多开发者的青睐? 由于 Rust 具有更强大的高并发性和高安全性,因此它可谓是栈溢出开发的完美选择。由于对函数的优秀控制能力和对内存布局的完美运用,使得 Rust 成为一种面向性能的编程语言。使用 Rust

Segmentation fault when using C callback user data to store a boxed Rust closure

ぃ、小莉子 提交于 2020-08-05 09:59:05
问题 I am creating a Rust wrapper around a C API. One function in this C API sets a callback and accepts a void pointer which will be passed to the callback. It stores a reference to the callback and user data for later, so I am using the last code section from this answer. Here is my code. The Test::trigger_callback(...) function is meant to emulate the C library calling the callback. extern crate libc; use libc::c_void; use std::mem::transmute; struct Test { callback: extern "C" fn(data: i32,

Why does the reqwest HTTP library return binary data instead of a text body?

≯℡__Kan透↙ 提交于 2020-08-05 07:44:06
问题 I am trying to perform a HTTP GET request with reqwest and print the response body to STDOUT. This works for most websites, but it returns weird binary output for amazon.com: #[tokio::main] async fn main() { run().await; } async fn run() { let url = "https://www.amazon.com/PNY-GeForce-Gaming-Overclocked-Graphics/dp/B07GJ7TV8L/"; let resp = reqwest::get(url).await.unwrap(); let text = resp.text().await.unwrap(); println!("{}", text); } Why would resp.text().await.unwrap() return binary data

What can ref do that references couldn't?

99封情书 提交于 2020-08-05 07:11:21
问题 What can ref do that references couldn't? Could match value.try_thing() { &Some(ref e) => do_stuff(e), // ... } not be equally expressed by match value.try_thing() { &Some(e) => do_stuff(&e), // ... } 回答1: No, it is not avoidable with your proposed syntax. Your syntax does not allow for taking a reference when otherwise a move would be permissable. In this example, inner is a copy of the integer from val and changing it has no effect on val : fn main() { let mut val = Some(42); if let &mut

Unable to find crate that is listed in [build-dependencies] section

倖福魔咒の 提交于 2020-08-04 21:52:04
问题 I try to compile my project with the command cargo build . build.rs extern crate csv; use std::path::Path; use std::fs::OpenOptions; use std::io::BufWriter; use std::io::Write; #[allow(non_snake_case)] fn processCSV(filename: &str, sourcePath: &str, enumName: &str) { println!("Generate rust source code from schema {}",filename); let mut ret: Vec<String> = Vec::new(); let mut rdr = csv::Reader::from_file(filename).unwrap().flexible(true); for record in rdr.records().map(|r| r.unwrap()) { } let

Unable to find crate that is listed in [build-dependencies] section

江枫思渺然 提交于 2020-08-04 21:51:25
问题 I try to compile my project with the command cargo build . build.rs extern crate csv; use std::path::Path; use std::fs::OpenOptions; use std::io::BufWriter; use std::io::Write; #[allow(non_snake_case)] fn processCSV(filename: &str, sourcePath: &str, enumName: &str) { println!("Generate rust source code from schema {}",filename); let mut ret: Vec<String> = Vec::new(); let mut rdr = csv::Reader::from_file(filename).unwrap().flexible(true); for record in rdr.records().map(|r| r.unwrap()) { } let