我正在尝试将glium与cgmath接口。按照这个答案,我实现了一个ToArray特征,将的实例转换cgmath::Matrix4为glium可以使用的格式:
pub trait ToArray {
type Output;
fn to_array(&self) -> Self::Output;
}
impl<S: cgmath::BaseNum> ToArray for cgmath::Matrix4<S> {
type Output = [[S; 4]; 4];
fn to_array(&self) -> Self::Output {
(*self).into()
}
}
Run Code Online (Sandbox Code Playgroud)
由于我并不总是Matrix4直接使用,因此我需要对cgmath转换类型进行类似的实现。例如cgmath::Decomposed:
impl<S: cgmath::BaseFloat, R: cgmath::Rotation3<S>> ToArray
for cgmath::Decomposed<cgmath::Vector3<S>, R> {
type Output = [[S; 4]; 4];
fn to_array(&self) -> Self::Output {
cgmath::Matrix4::<S>::from(*self).into()
}
}
Run Code Online (Sandbox Code Playgroud)
这可行,但是我想避免为所有转换类型重复代码,所以我认为我将为可以转换为的任何东西定义一个通用实现Matrix4:
impl<S: cgmath::BaseFloat, T: Into<cgmath::Matrix4<S>>> ToArray for T {
type Output = …Run Code Online (Sandbox Code Playgroud) 我正在尝试编写一个生成结构的宏.结构的实现将由宏生成,但是一些代码块将作为宏参数提供.以下是此类宏的最小示例:
macro_rules! make_struct {
($name:ident $block:block) => {
struct $name {
foo: i32,
}
impl $name {
fn new() -> Self {
$name { foo: 42 }
}
fn act (&self) {
$block
}
}
};
}
Run Code Online (Sandbox Code Playgroud)
以下是如何使用宏的示例:
fn main() {
// Works
make_struct!(Test { println! ("Bar: {:?}", 24); });
let test = Test::new();
test.act();
}
Run Code Online (Sandbox Code Playgroud)
我想提供访问self内部提供的代码.就像是:
fn main() {
// Does not work
make_struct!(Test { println! ("Foo: {:?}", self.foo); });
let test = Test::new();
test.act();
}
Run Code Online (Sandbox Code Playgroud)
据我所知,由于宏观卫生规则,这不起作用.具体而言, …
我是一名 Java 开发人员,正在学习 Rust。这是一个小例子,它将当前目录的文件名读入一个字符串列表/向量,然后输出它。
带有 nio 的 Java:
import java.io.*;
import java.nio.file.*;
import java.util.*;
import java.util.stream.*;
public class ListFileNames {
public static void main(String[] args) {
final Path dir = Paths.get(".");
final List<String> fileNames = new ArrayList<>();
try {
final Stream<Path> dirEntries = Files.list(dir);
dirEntries.forEach(path -> {
if (Files.isRegularFile(path)) {
fileNames.add(path.getFileName().toString());
}
});
}
catch (IOException ex) {
System.err.println("Failed to read " + dir + ": " + ex.getMessage());
}
print(fileNames);
}
private static void print(List<String> names) {
for (String …Run Code Online (Sandbox Code Playgroud) 我在从 RefCell<Option<Rc>> 获取引用时遇到问题。
有什么建议吗?
struct Node<T> {
value: T
}
struct Consumer3<T> {
tail: RefCell<Option<Rc<Node<T>>>>,
}
impl<T> Consumer3<T> {
fn read<'s>(&'s self) -> Ref<Option<T>> {
Ref::map(self.tail.borrow(), |f| {
f.map(|s| {
let v = s.as_ref();
v.value
})
})
}
}
Run Code Online (Sandbox Code Playgroud)
给出:
struct Node<T> {
value: T
}
struct Consumer3<T> {
tail: RefCell<Option<Rc<Node<T>>>>,
}
impl<T> Consumer3<T> {
fn read<'s>(&'s self) -> Ref<Option<T>> {
Ref::map(self.tail.borrow(), |f| {
f.map(|s| {
let v = s.as_ref();
v.value
})
})
}
}
Run Code Online (Sandbox Code Playgroud)
我想将一个对象放入 serde_json::Map 中,其中键将是该对象内部的值。
use serde_json::{json, Map, Value};
fn main() {
let a = json!({
"x": "y"
});
let mut d: Map<String, Value> = Map::new();
d[&a["x"].to_string()] = a;
}
Run Code Online (Sandbox Code Playgroud)
错误:
borrow of moved value: `a`
value borrowed here after moverustcE0382
main.rs(9, 30): value moved here
main.rs(4, 9): move occurs because `a` has type `Value`, which does not implement the `Copy` trait
Run Code Online (Sandbox Code Playgroud) 我有一个字符迭代器,我想每 N 个字符添加一个换行符:
let iter = "abcdefghijklmnopqrstuvwxyz".chars();
let iter_with_newlines = todo!();
let string: String = iter_with_newlines.collect();
assert_eq("abcdefghij\nklmnopqrst\nuvwxyz", string);
Run Code Online (Sandbox Code Playgroud)
所以基本上,我想在迭代器中每 n 个字符散布一个换行符。我怎样才能做到这一点?
如果我能做这样的事情那就太好了,哪里chunks有一种方法可以制作Iterator<T>成Iterator<Iterator<T>:iter.chunks(10).intersperse('\n').flatten()
如果我能做这样的事情那就太酷了:iter.chunks.intersperseEvery(10, '\n'),其中intersperseEvery是一种仅将值散布在每 n 个项目中的方法。
我是 Rust lang 的新手。-> _返回对于函数来说意味着什么rocket?
#[launch]
fn rocket() -> _ {
rocket::build()
.attach(json::stage())
.attach(msgpack::stage())
.attach(uuid::stage())
}
Run Code Online (Sandbox Code Playgroud) 为什么不能返回 Rust 中临时对象的引用?激励性的例子是:
fn what<'cellref, 'cell: 'cellref>(x: &f64) -> &'cellref CellValue<'cell> {
&CellValue::Number(*x)
}
Run Code Online (Sandbox Code Playgroud)
人们可能认为编译器可以推断只要引用存在,该对象就需要存在,因此使其保持活动状态,直到引用被删除。为什么编译器不能推断出这一点?
根据要求,这是 MRE。它说明了一个简单的问题:假设 API 需要一个&T. 您将其存放在哪里,T以便其可以按照需要的时间持续使用&T?
pub enum CellValue<'a> {
String(&'a String),
Number(f64),
Boolean(bool),
// ... many more types ...
}
pub enum Array<'a> {
ArrayGeneric(ndarray::Array2<CellValue<'a>>),
ArrayF64(ndarray::Array2<f64>),
ArrayString(ndarray::Array2<f64>),
// .. many more types ...
}
impl Array<'a> {
pub fn generic_iter() -> Iterator<Item = &CellValue> {
// ?
}
}
Run Code Online (Sandbox Code Playgroud)
与许多 Rust 用例一样,目标是零成本的抽象。
作为动机,假设您有一个 Excel 电子表格,并且您正在定义一个可以在 Excel 函数之间传递的单元格“数组”。有时,这实际上是电子表格中的值范围。在其他时候,您可能已经应用了转换,例如ABS(...),现在您拥有了一系列单元格的绝对值的数组。在前一种情况下,您只需要存储完整的电子表格和一些 …
我正在读关于?运算符并想在没有类型的函数中使用它Result<T, E>。下面提到的部分写在其中:
\n\n此错误指出我们\xe2\x80\x99re 只允许在返回、或实现 的其他类型的
\n?函数中使用运算符。ResultOptionFromResidual要修复该错误,您有两种选择。一种选择是更改函数的返回类型,使其与您使用运算符的值兼容,
\n?只要您没有任何限制即可。另一种技术是使用匹配或其中一种方法以任何适当的方式Result<T, E>来处理。Result<T, E>
我没有看到这个的实现,只是在语句之前写 match 与 ? 不起作用。\n我如何捕获该错误并使用它为我的函数返回一些其他依赖值。
\n我的代码看起来像这样(显然,它没有运行)...我对实现相同功能的其他方式并不真正感兴趣,相反,我问是否可以使用这个具有此特定配置的特定操作员。
\nfn error_handling() -> String{\n\n //the ? operator (replaces the try macro)\n //Shorthand, passes the Ok() value out while returns the Err() value.\n //Also can pass the Some() value from Option<T> and return None value.\n //\n //If function doesn\'t have the return type as Result<T, E> …Run Code Online (Sandbox Code Playgroud) 这是我使用的模式:
\n"\\w+|[^\\w\\s]+"\nRun Code Online (Sandbox Code Playgroud)\n当我匹配字符串“abc.efg”和“\xe6\x88\xa6\xe5\xa0\xb4\xe3\x81\xae\xe3\x83\xb4\xe3\x82\xa1\xe3\x83\xab\xe3\ x82\xad\xe3\x83\xa5\xe3\x83\xaa\xe3\x82\xa23" 在https://regexr.com/中使用 PCRE ,\nit 给我这样的结果:
\n"abc" "." "efg" => 3 parts\n\n"\xe6\x88\xa6\xe5\xa0\xb4\xe3\x81\xae\xe3\x83\xb4\xe3\x82\xa1\xe3\x83\xab\xe3\x82\xad\xe3\x83\xa5\xe3\x83\xaa\xe3\x82\xa2" "3" => 2 parts\nRun Code Online (Sandbox Code Playgroud)\n看起来是对的。
\n但是当我像这样使用 icu 时:
\n //std::string ldata = "abc.efg";\n std::string ldata = "\xe6\x88\xa6\xe5\xa0\xb4\xe3\x81\xae\xe3\x83\xb4\xe3\x82\xa1\xe3\x83\xab\xe3\x82\xad\xe3\x83\xa5\xe3\x83\xaa\xe3\x82\xa23";\n std::string m_regex = "\\\\w+|[^\\\\w\\\\s]+";\n UErrorCode status = U_ZERO_ERROR;\n icu::RegexMatcher matcher(m_regex.c_str(), 0, status);\n icu::StringPiece data((char*)ldata.data(), ldata.length());\n icu::UnicodeString input = icu::UnicodeString::fromUTF8(data);\n matcher.reset(input);\n \n \n int count = 0;\n while (matcher.find(status) && U_SUCCESS(status))\n {\n auto start_index = matcher.start(status);\n auto end_index = matcher.end(status);\n count++; \n }\n …Run Code Online (Sandbox Code Playgroud)