web3我正在使用板条箱中的类型,web3::contract::Contract<web3::transports::Http>. 编译器抱怨E0277:
$ cargo run
Compiling proj v0.1.0 (/home/user/proj)
error[E0277]: the trait bound `web3::contract::Contract<web3::transports::Http>: Default` is not satisfied
--> src/book.rs:38:5
|
38 | / #[serde(skip)]
39 | | abi: web3::contract::Contract<OMETransport>,
| |_______________________________________________^ the trait `Default` is not implemented for `web3::contract::Contract<web3::transports::Http>`
|
= note: required by `std::default::Default::default`
error: aborting due to previous error
For more information about this error, try `rustc --explain E0277`.
error: could not compile `proj`
To learn more, run the command again …Run Code Online (Sandbox Code Playgroud) 我想实现一个允许分配泛型类型的特征。到目前为止,我已经测试了以下u32类型String:
trait Test {
fn test(&self, input: &str) -> Self;
}
impl Test for String {
fn test(&self, input: &str) -> Self {
input.parse().unwrap()
}
}
impl Test for u32 {
fn test(&self, input: &str) -> Self {
input.parse().unwrap()
}
}
fn main() {
let mut var = 0u32;
let mut st = String::default();
var = var.test("12345678");
st = st.test("Text");
println!("{}, {}", var, st);
}
Run Code Online (Sandbox Code Playgroud)
我知道这段代码并不完美,我应该使用Result返回而不是展开,但请将其放在一边,因为这是一个简单的示例。u32和 的实现String完全相同,因此我想对两者使用默认实现,而不是复制和粘贴代码。我尝试过使用其中之一,但由于Self两者返回的类型不同,编译器无法确定类型大小和错误。
在这种情况下我该如何编写默认实现?
我是 Rust 新手,正在阅读官方书籍。我正在研究一个简单的 grep 示例,并希望创建一个exit可以在不同地方使用的函数。不幸的是,在闭包中使用此函数unwrap_or_else会导致编译错误。我不清楚为什么,因为当我直接在闭包中使用函数的内容时,它会起作用。
这是我的main.rs文件:
use std::env;
use std::fs;
use std::process;
use std::error::Error;
use std::fmt::Display;
struct Config{
query: String,
filename: String,
}
impl Config {
fn new(input: &[String]) -> Result<Config, &'static str> {
if input.len() < 3 {
return Err("Not enough arguments provided.");
}
let query = input[1].clone();
let filename = input[2].clone();
Ok(Config { query, filename })
}
}
fn run(cfg: Config) -> Result<(), Box<dyn Error>> {
let contents = fs::read_to_string(&cfg.filename)?;
contents.find(&cfg.query).expect("Corrupted text …Run Code Online (Sandbox Code Playgroud) 如何克隆带有结构项的向量Rust。
我已经尝试过.to_vec(),但似乎我不能,因为我正在使用结构。
struct Abc {
id: u32,
name: String
}
let mut vec1: Vec<Abc> = vec![];
let item1 = Abc {
id: 1,
name: String::from("AlgoQ")
}
vec1.push(item1)
let vec2 = vec1.to_vec();
Run Code Online (Sandbox Code Playgroud)
错误:
the trait bound `blabla::Abc: Clone` is not satisfied
the trait `Clone` is not implemented for `blabla::Abc`rustc(E0277)
Run Code Online (Sandbox Code Playgroud) Point并Vec2使用相同的变量和完全相同的构造函数定义:
pub struct Point {
pub x: f32,
pub y: f32,
}
pub struct Vec2 {
pub x: f32,
pub y: f32,
}
impl Point {
pub fn new(x: f32, y: f32) -> Self {
Self { x, y }
}
}
impl Vec2 {
pub fn new(x: f32, y: f32) -> Self {
Self { x, y }
}
}
Run Code Online (Sandbox Code Playgroud)
是否可以定义一个特征来实现构造函数?
到目前为止,我发现只能定义接口,因为内部变量未知:
pub trait TwoDimensional {
fn new(x: f32, y: f32) -> Self;
}
Run Code Online (Sandbox Code Playgroud) 我正在编写一个特征作为映射类型数据结构(例如std::collections::BTreeMap和std::collections::HashMap)的接口。这是我昨天提出的问题的后续,尽管它是独立的。
我有一个我似乎无法理解的终生问题。我在我所有的教科书、The Rust Reference、StackOverflow 等中寻找答案,但我一直无法弄清楚发生了什么。根据上一个问题的建议,我已经在以下代码中编写了近十几个变体,并且最终遇到了相同的情况。我希望有人能帮助我理解为什么gc3()不可能或者我做错了什么。我知道我完全有可能已经关注这个问题太久了,以至于错过了一些本应显而易见的简单内容。(游乐场)
use std::collections::hash_map::{HashMap, Iter};
fn main() {
gc1(&HashMap::new());
gc2(&HashMap::new());
gc3(HashMap::new());
}
// Works
fn gc1<'a>(map: &'a dyn GroupedCollection<'a, usize, usize, Iter<'a, usize, Vec<usize>>>) {
let _ = map.iter().collect::<Vec<_>>();
}
// Works
fn gc2<'a, M>(map: &'a M)
where
M: 'a + GroupedCollection<'a, usize, usize, Iter<'a, usize, Vec<usize>>>,
{
let _ = map.iter().collect::<Vec<_>>();
}
// Compiler error: `map` does not live long enough
fn gc3<'a, M>(map: …Run Code Online (Sandbox Code Playgroud) 我在阅读 Rust 时遇到了这个特征定义:
trait Enchanter: std::fmt::Debug {
...
}
Run Code Online (Sandbox Code Playgroud)
由此我了解到该特征的名称是Enchanter,但我不明白该std::Format:Debug部分意味着什么,因为它也是一个特征(我认为)。
我正在构建一个渲染引擎,我想要的一件事是处理任意网格数据的管理,无论表示如何。
我的想法是,定义一个特征来强制执行函数签名,然后当我处理所有 GPU 内容时,用户可以处理序列化。这就是我所创造的特质:
pub enum GpuAttributeData
{
OwnedData(Vec<Vec<i8>>, Vec<u32>),
}
pub trait GpuSerializable
{
fn serialize(&self) -> GpuAttributeData;
}
Run Code Online (Sandbox Code Playgroud)
非常简单,给我几个数组。
当我测试板条箱内的东西时,它起作用了,但我将示例移到了板条箱外,即我在示例中包含以下代码片段:
impl <const N : usize> GpuSerializable for [Vertex; N]
{
fn serialize(&self) -> GpuAttributeData
{
let size = size_of::<Vertex>() * self.len();
let data = unsafe {
let mut data = Vec::<i8>::with_capacity(size);
copy_nonoverlapping(
self.as_ptr() as *const i8, data.as_ptr() as *mut i8, size);
data.set_len(size);
data
};
// let indices : Vec<usize> = (0..self.len()).into_iter().collect();
let indices = vec![0, 1, 2];
let …Run Code Online (Sandbox Code Playgroud) 我想要一个Vec<CustomType>可以加入的&str。这是我到目前为止所尝试过的:
#[derive(Debug)]
struct Item {
string: String,
}
impl Item {
pub fn new(string: impl Into<String>) -> Self {
Self {
string: string.into(),
}
}
pub fn to_string(&self) -> &String {
&self.string
}
}
impl From<&Item> for &String {
fn from(item: &Item) -> Self {
&item.string
}
}
impl From<&Item> for &str {
fn from(item: &Item) -> Self {
&item.string.to_string()
}
}
fn main() {
let items = Vec::from([Item::new("Hello"), Item::new("world")]);
let string = items.join(" ");
println!("{}", …Run Code Online (Sandbox Code Playgroud) 因此,我正在尝试构建自定义类型的向量的向量。我正在尝试为其实现默认值,并且通过 for 循环取得了成功。
let mut data: Vec<Vec<Cell>> = Vec::new();
for _i in 0..63 {
let mut row: Vec<Cell> = Vec::with_capacity(64);
for _j in 0..63 {
row.push(Cell::default())
}
data.push(row);
}
Run Code Online (Sandbox Code Playgroud)
我觉得这段代码可以使用一些函数式风格和交互器,所以我决定这样做:
let data: Vec<Vec<Cell>> = Vec::with_capacity(64)
.iter_mut()
.map(|mut x: &mut Vec<Cell>| {
x = Vec::with_capacity(64)
.iter_mut()
.map(|mut y: Cell| y = Cell::default())
.collect()
})
.collect();
Run Code Online (Sandbox Code Playgroud)
这样,我收到如下错误:
error[E0631]: type mismatch in closure arguments
--> src/types.rs:124:26
|
124 | .map(|mut y: Cell| y = Cell::default())
| ^^^ ------------- found signature defined here …Run Code Online (Sandbox Code Playgroud)