有没有一种好方法可以完美地转发模板化类中的函数?具体来说,在代码中
#include <iostream>
// Forward declare a Bar
struct Bar;
// Two different functions that vary based on the kind of argument
void printme(Bar const & bar) {
std::cout << "printme: constant reference bar" << std::endl;
}
void printme(Bar && bar) {
std::cout << "printme: r-value reference bar" << std::endl;
}
void printme2(Bar const & bar) {
std::cout << "printme2: constant reference bar" << std::endl;
}
void printme2(Bar && bar) {
std::cout << "printme2: r-value reference bar" << std::endl;
} …Run Code Online (Sandbox Code Playgroud) 有没有办法在 Rust 中保存通用随机数生成器?我想要一种编写通用代码的方法,例如:
use rand::Rng; // 0.7.2
fn main() {
// Purely random numbers on the interval 0 to 1
println!("Pure random");
let mut rng: Box<dyn rand::Rng> = Box::new(rand::thread_rng());
for i in 0..10 {
println!("{}", rng.gen::<f64>());
}
println!("");
// On a seed
*rng = rand::SeedableRng::seed_from_u64(0);
for i in 0..10 {
println!("{}", rng.gen::<f64>());
}
println!("");
}
Run Code Online (Sandbox Code Playgroud)
该变量rng使用种子或其他方式保存不同类型的随机数生成器。然而,这段代码存在很多错误,例如:
use rand::Rng; // 0.7.2
fn main() {
// Purely random numbers on the interval 0 to 1
println!("Pure random");
let mut rng: …Run Code Online (Sandbox Code Playgroud) 使用包含返回引用的方法的特征对象的正确方法是Self什么?以下代码
trait Foo {
fn gen(&mut self) -> &Self;
fn eval(&self) -> f64;
}
struct A {
a : f64,
}
impl Foo for A {
fn gen(&mut self) -> &Self {
self.a = 1.2;
self
}
fn eval(&self) -> f64 {
self.a + 2.3
}
}
struct B;
impl Foo for B {
fn gen(&mut self) -> &Self {
self
}
fn eval(&self) -> f64 {
3.4
}
}
fn bar(f : &dyn Foo) {
println!("Result is …Run Code Online (Sandbox Code Playgroud) 可以将 trait 类型的对象IntoIterator装箱并保存在结构内吗?我有一种情况,我想存储一个可以变成迭代器的对象向量。我在这方面的尝试是代码
struct Foo {
foo: Vec<Box<dyn IntoIterator<Item = usize>>>,
}
fn main() {
let _ = Foo {
foo: vec![Box::new(1..2), Box::new(vec![2,4,4])],
};
}
Run Code Online (Sandbox Code Playgroud)
但是,这不会编译并产生错误:
error[E0191]: the value of the associated type `IntoIter` (from trait `IntoIterator`) must be specified
--> src/main.rs:6:22
|
6 | foo: Vec<Box<dyn IntoIterator<Item = usize>>>,
| ^^^^^^^^^^^^^^^^^^^^^^^^^^ help: specify the associated type: `IntoIterator<Item = usize, IntoIter = Type>`
error: aborting due to previous error
For more information about this error, try `rustc --explain …Run Code Online (Sandbox Code Playgroud) F#是否有行多态或类似的东西?具体来说,在OCaml中,我们可以编写一个类似的函数
# let foo x = x#num+2;;
val foo : < num : int; .. > -> int = <fun>
Run Code Online (Sandbox Code Playgroud)
基本上,该函数foo可以接受包含num类型方法的任何对象int.我不知道如何在F#中做类似的事情.如果可能的话,我想避免通过继承进行显式的子类型化.具体来说,我不是在寻找这样的东西:
[<AutoOpen>]
module Foo
[<AbstractClass>]
type foo() =
abstract member num : int
type foo1() =
inherit foo()
override this.num = 2
member this.char = 'a'
type foo2() =
inherit foo()
override this.num = 3
member this.string = "abbacadabba"
let f (x:foo) = x.num + 2
Run Code Online (Sandbox Code Playgroud)
其原因是,即使我们可以使用类型的对象foo1和foo2内部f …
如何在GADT上进行模式匹配?在这种情况下,我在使用Bigarray的GADT时遇到了麻烦。更具体地说,代码
let print_layout v = match Bigarray.Genarray.layout v with
| Bigarray.C_layout -> Printf.printf "C layout\n"
| Bigarray.Fortran_layout -> Printf.printf "Fortran layout\n"
Run Code Online (Sandbox Code Playgroud)
无法编译错误消息
Error: This pattern matches values of type
Bigarray.fortran_layout Bigarray.layout
but a pattern was expected which matches values of type
Bigarray.c_layout Bigarray.layout
Type Bigarray.fortran_layout is not compatible with type
Bigarray.c_layout
Run Code Online (Sandbox Code Playgroud)
它在抱怨这个Bigarray.Fortran_layout案子。如果我们看一下Bigarray我们看到,
type c_layout = C_layout_typ
type fortran_layout = Fortran_layout_typ
type 'a layout =
C_layout : c_layout layout
| Fortran_layout : fortran_layout layout
Run Code Online (Sandbox Code Playgroud)
因此,这是GADT,我在模式匹配方面做错了。什么是工作版本print_layout?
在OCaml中的不可变记录或对象更新期间,对象之间共享了多少内存?例如,对于代码中的记录:
type foo = {
a : int;
b : int;
c : int}
let f1 = {a = 1; b=2; c=3}
let f2 = {f1 with c=4}
Run Code Online (Sandbox Code Playgroud)
f1和之间共享多少内存f2?基本上,他们共享内存a和b?同样,对于代码中的对象:
type ('i, 'j) lens = { get : 'j; set : 'j -> 'i }
class bar = object
val a = 1
method a = {
get = a;
set = fun a' -> {< a = a' >}
}
val b = …Run Code Online (Sandbox Code Playgroud) 如何在Rust中处理分布式内存并行性?通过这种方式,我的意思是语言结构,库或其他功能来处理类似于MPI提供C的集群之类的计算,但不一定使用相同的原语或方法.在Rustonomicon中,我看到了对线程和并发性的讨论,但我没有看到有关跨多台计算机并行化的讨论.
使用X宏时,处理额外尾随逗号的最佳方法是什么?具体来说,我在文件中有以下设置test01.cpp
struct Foo {
#define X(name,val) int name;
#include "test01.def"
#undef X
Foo() :
#define X(name,val) name(val),
#include "test01.def"
#undef X
{}
};
int main(){
Foo foo;
}
Run Code Online (Sandbox Code Playgroud)
在test01.def,我有
X(foo,1)
X(bar,23)
Run Code Online (Sandbox Code Playgroud)
由于错误,这不会编译
test01.cpp: In constructor 'Foo::Foo()':
test01.cpp:10:5: error: expected identifier before '{' token
{}
Run Code Online (Sandbox Code Playgroud)
基本上,在成员初始化列表中的最后一个元素之后有一个尾随逗号.现在,我们可以通过添加虚拟变量来解决这个问题:
struct Foo {
private:
void * end;
public:
#define X(name,val) int name;
#include "test01.def"
#undef X
Foo() :
#define X(name,val) name(val),
#include "test01.def"
#undef X
end(nullptr)
{}
};
int main(){
Foo foo; …Run Code Online (Sandbox Code Playgroud) 是否有一个很好的方法来获取参数并返回类型,std::function以便我们还返回cv和引用限定符?这部分涉及到前一个问题在这里.无论如何,使用答案中的代码,我们有以下示例:
#include <functional>
#include <iostream>
template<typename T>
struct function_traits;
template<typename R, typename ...Args>
struct function_traits<std::function<R(Args...)>> {
static const size_t nargs = sizeof...(Args);
typedef R result_type;
template <size_t i>
struct arg {
typedef typename std::tuple_element<i, std::tuple<Args...>>::type
type;
};
};
template <typename T>
void foo(T const & f) {
typedef function_traits <T> stuff;
std::cout <<
typeid(typename function_traits <T>::result_type).name()
<< std::endl;
std::cout <<
typeid(typename function_traits <T>::template arg<0>::type).name()
<< std::endl;
std::cout << typeid(T).name() << std::endl;
}
int main() {
std::cout …Run Code Online (Sandbox Code Playgroud) 也许我的术语是错误的,但是有没有一种方法可以使用后缀表示法在Rust中调用函数而不定义新特性?基本上,我有一个向量,&str并且我想将它们转换为带符号的字符串myvec.as_string()。目前,我可以使用代码执行此操作
trait Foo {
fn as_string(&self) -> String;
}
impl Foo for Vec<&str> {
fn as_string(&self) -> String {
let mut mystr = self
.iter()
.fold(String::new(),|sum,s| format!("{}{}:", sum, s));
mystr.pop();
mystr
}
}
fn main() {
let my_vec = vec!["bar", "buz", "baz"];
use crate::Foo;
println!("{}", my_vec.as_string());
}
Run Code Online (Sandbox Code Playgroud)
就是说,为了完成这项工作,我需要定义一个Foo我并不真正在意的特性,并且需要use crate::Foo在调用to之前打开该特性as_string。有没有更好的方法可以做到这一点?而且,要明确一点,我想尽可能避免使用该表示法as_string(myvec),因为后缀表示法非常适合将命令链接在一起。
Copy在Rust 中缺少的元素的借入向量上计算算术运算的正确方法是什么?在下面的代码中,我想foo借用一个向量x,然后计算一个短函数。诀窍在于元素中x必然缺少Copy特质。无论如何,代码
fn foo<Real>(x: &Vec<Real>) -> Real
where
Real: std::ops::Add<Output = Real> + std::ops::Mul<Output = Real> + Clone,
{
(x[0] + x[1]) * x[2]
}
fn main() {
let x = vec![1.2, 2.3, 3.4];
let _y = foo::<f64>(&x);
}
Run Code Online (Sandbox Code Playgroud)
无法编译错误
error[E0507]: cannot move out of index of `std::vec::Vec<Real>`
--> src/main.rs:5:6
|
5 | (x[0] + x[1]) * x[2]
| ^^^^ move occurs because value has type `Real`, which does not implement …Run Code Online (Sandbox Code Playgroud) 有没有办法获取 Rust 中初始化值的位置和文件名?我知道file!和line!宏,但它们提供了它们最初被调用的位置的信息,并且我希望从初始化值的位置确定此信息。例如,以下代码不起作用,但与我想要的类似:
// Contains a value as well as where this value was initialized
struct Foo {
value : usize,
file : String,
line : u32,
}
impl Foo {
fn new(value : usize) -> Foo {
Foo {
value,
file : String::from(std::file!()),
line : std::line!(),
}
}
}
// Test the result
fn main() {
let foo1 = Foo::new(0);
println!("foo1 created in file \"{}\" line {}",foo1.file,foo1.line);
let foo2 = Foo::new(1);
println!("foo2 created in file …Run Code Online (Sandbox Code Playgroud)