为什么这样:
#include <string>
#include <iostream>
using namespace std;
class Sandbox
{
public:
Sandbox(const string& n) : member(n) {}
const string& member;
};
int main()
{
Sandbox sandbox(string("four"));
cout << "The answer is: " << sandbox.member << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
给出输出:
答案是:
代替:
答案是:四
为什么这段代码会编译?
fn get_iter() -> impl Iterator<Item = i32> {
[1, 2, 3].iter().map(|&i| i)
}
fn main() {
let _it = get_iter();
}
Run Code Online (Sandbox Code Playgroud)
[1, 2, 3]是一个局部变量并iter()借用它.此代码不应编译,因为返回的值包含对局部变量的引用.
我正在尝试实现一个常用的模式 - 在下一个循环迭代中使用上一个循环迭代的结果。例如,要实现分页,您需要给出上一页上最后一个值的 id。
struct Result {
str: String,
}
fn main() {
let times = 10;
let mut last: Option<&str> = None;
for i in 0..times {
let current = do_something(last);
last = match current {
Some(r) => Some(&r.str.to_owned()),
None => None,
};
}
}
fn do_something(o: Option<&str>) -> Option<Result> {
Some(Result {
str: "whatever string".to_string(),
})
}
Run Code Online (Sandbox Code Playgroud)
但是,我不确定如何真正从循环中获取值。目前,编译器错误是temporary value dropped while borrowed(at &r.str.to_owned()),虽然我做了很多其他尝试,但都无济于事。
我发现真正让它工作的唯一方法是创建某种局部tmp_str变量并像这样进行黑客攻击:
match current {
Some(r) => {
tmp_str.clone_from(&r.str);
last = …Run Code Online (Sandbox Code Playgroud) 我有这样的功能:
extern {
fn foo(layout: *const RawLayout) -> libc::uint8_t;
}
fn bar(layout: Layout) -> bool {
unsafe {
foo(&layout.into() as *const _) != 0
}
}
Run Code Online (Sandbox Code Playgroud)
Layout可转换.into()的可复制类型在哪里RawLayout?
我想确保我理解发生的事情,因为它不安全.据我所知,layout.into()创建一个临时的RawLayout,然后&对它进行引用,as *const _并将其转换为原始指针(*const RawLayout).然后foo()调用该函数并返回,最后RawLayout删除临时函数.
那是对的吗?还是有一些棘手的原因我不应该这样做?
当前版本的The Rustonomicon有这个示例代码:
use std::mem;
pub struct IterMut<'a, T: 'a>(&'a mut [T]);
impl<'a, T> Iterator for IterMut<'a, T> {
type Item = &'a mut T;
fn next(&mut self) -> Option<Self::Item> {
let slice = mem::replace(&mut self.0, &mut []);
if slice.is_empty() {
return None;
}
let (l, r) = slice.split_at_mut(1);
self.0 = r;
l.get_mut(0)
}
}
Run Code Online (Sandbox Code Playgroud)
我特别对这条线感到困惑:
let slice = mem::replace(&mut self.0, &mut []);
// ^^^^^^^
Run Code Online (Sandbox Code Playgroud)
这个借书怎么查?如果这是一个不可变的借用,RFC 1414指出[]右值应该有'static生命周期,这样一个不可变的借用会借用检查,但这个例子显示了一个可变的借用!似乎必须发生两件事之一:
[]是临时的(以便它可以可变地使用),在这种情况下它没有'static生命周期,并且不应该借用检查;我有以下程序:
fn main() {
let x = 0;
println!("Example 1: {:p}", &x);
println!("Example 1: {:p}", &x);
println!("Example 2: {:p}", &&x);
println!("Example 2: {:p}", &&x);
}
Run Code Online (Sandbox Code Playgroud)
这是一个示例输出:
Example 1: 0x7ffcb4e72144
Example 1: 0x7ffcb4e72144
Example 2: 0x7ffcb4e72238
Example 2: 0x7ffcb4e72290
Run Code Online (Sandbox Code Playgroud)
for 的输出"Example 1"始终相同,而 for的输出"Example 2"始终不同。
我已经阅读了是否 println! 借用或拥有变量?,而我从给定的答案中了解到的是,println!默默地参考。换句话说,这听起来像是println!增加了一个额外的间接级别。
我原以为输出"Example 1"也会有所不同。看到它println!悄悄地采取了另一个间接级别,"Example 1"实际上正在与 一起工作&&x,并且"Example 2"正在与 一起工作&&&x。这似乎与我链接的答案一致,特别是:"If you write println!("{}", &x), you …
我正在尝试使用Select条板箱抓取网页:
let document = Document::from_read(response).unwrap();
for node in document.find(Class("lia-list-row")) {
let title = node.find(Class("page-link")).next().unwrap();
let title_text = title.text().trim();
println!("{}\n", title_text);
}
Run Code Online (Sandbox Code Playgroud)
导致以下错误:
let document = Document::from_read(response).unwrap();
for node in document.find(Class("lia-list-row")) {
let title = node.find(Class("page-link")).next().unwrap();
let title_text = title.text().trim();
println!("{}\n", title_text);
}
Run Code Online (Sandbox Code Playgroud)
我通过将.text()和分开来解决了.trim()
let title_text = title.text();
let trim_text = title_text.trim();
Run Code Online (Sandbox Code Playgroud)
有什么不同?为什么第一次尝试失败?
我想为引用和非引用类型实现一个特征。我是否必须两次实现这些功能,或者这样做不是惯用的?
这是演示代码:
struct Bar {}
trait Foo {
fn hi(&self);
}
impl<'a> Foo for &'a Bar {
fn hi(&self) {
print!("hi")
}
}
impl Foo for Bar {
fn hi(&self) {
print!("hi")
}
}
fn main() {
let bar = Bar {};
(&bar).hi();
&bar.hi();
}
Run Code Online (Sandbox Code Playgroud) 当在Rust中将指向函数的原始指针存储在Rust中时,程序的行为可能会根据原始指针的可变性以意想不到的方式改变。
使用const指针可以得到预期的结果。
也可以在操场上查看以下代码:
type ExternFn = unsafe extern "C" fn() -> ();
unsafe extern "C" fn test_fn() {
println!("Hello!");
}
mod mut_ptr {
use super::{ExternFn, test_fn};
#[derive(Debug, Eq, PartialEq)]
pub struct FunctionHolder {
function: *mut ExternFn,
}
impl FunctionHolder {
pub fn new() -> Self {
FunctionHolder {
function: (&mut (test_fn as ExternFn) as *mut _),
}
}
pub fn call(&self) {
if !self.function.is_null() {
unsafe { (&*self.function)(); }
}
}
}
}
mod const_ptr { …Run Code Online (Sandbox Code Playgroud) 我有一个接收一些参数的函数,但是当我尝试使用该参数时,它会抛出错误。
// 功能
pub fn solc_compile(compiler: &str, file: &str, out: &str, config: templates::Config) {
let mut args = vec![
"--bin",
"--abi",
"--include-path",
"./libs",
"--include-path",
"./node_modules",
"--output-dir",
out,
];
if config.compiler.optimize {
let runs: &str = config.compiler.runs.to_string().as_str();
args.push("--optimize");
args.push("--optimize-runs");
args.push(runs);
}
}
Run Code Online (Sandbox Code Playgroud)
// 在函数参数上使用的配置类型(config templates::Config)。
模板.rs
// config templates.
#[derive(Deserialize, Serialize)]
pub struct Config {
pub info: ConfigInfo,
pub compiler: ConfigCompiler,
}
// config.info templates.
#[derive(Deserialize, Serialize)]
pub struct ConfigInfo {
pub name: String,
pub license: String,
}
// config.compiler templates. …Run Code Online (Sandbox Code Playgroud)