3,634 questions
Advice
0
votes
2
replies
27
views
How can I tell the compiler I want a type to be of a certain shape and implement a trait in Rust?
Take this code:
pub struct Complex<T: SimdElement>(Simd<T, 2>) where Simd<T, 2>: StdFloat;
How would I express that I want the inner value to be of the same type as the trait bound?
...
-1
votes
0
answers
50
views
Can you explain why Rust compiler doesn't see this trait item? [closed]
I have to make a small modification to a Rust code, but I don't know this particular language. Here is a small struct Terminator:
use std::time::Duration;
use jagua_rs::Instant;
/// Generic trait for ...
0
votes
0
answers
33
views
Call GORM's .list() in trait with generic type
In my Grails 6 project, I'd like to add an additional feature to select domain classes, so I defined a custom trait.
trait MyDomainClassTrait<D> implements GormEntity<D> {}
// domain ...
1
vote
1
answer
73
views
Rust generic type results in trait not found anymore
Rust newbie here.
The following code throws a compiler error:
#![feature(portable_simd)]
use std::simd::Simd;
use std::simd::SimdElement;
fn test_mul<T: SimdElement, const N: usize>(x: [T; N]) ...
0
votes
0
answers
32
views
Returning general json data in a tauri specta app [duplicate]
I'm working on a tauri application, Fluster. I'm trying to add a method to parse general tabular data using polars, and then return that data as a vec of hashmaps.
I'm currently running into this ...
7
votes
1
answer
139
views
Trait object taking ownership self
I want to build an application that interfaces with various cameras. Which specific camera is determined at runtime based on which is available. However, all cameras send frames one by one. Thus, to ...
1
vote
1
answer
102
views
How do I specialize the implementation of a function or struct for a single type?
Let's say I have a function that knows how to poll a no-result future in a way specific to my environment:
/// Poll the supplied future in some special way until it becomes ready.
fn poll_until_ready&...
2
votes
1
answer
90
views
Borrow value does not live long enough in lifetimed trait
I have the following (simplified) setup using the chumsky crate. Inputs to chumsky parsers require lifetimes in order to get zero-copy. I'm setting up traits to help enforce consistent parsing ...
0
votes
0
answers
54
views
How to override traits error response structure in raml
There is a trait defined for error response which has all error codes but for few resources I want to update a separate error response for few error codes like 400,403. I defined the 400 error data ...
1
vote
1
answer
122
views
How to avoid type annotations when using associated types in Rust?
I'm trying to adapt some old sample DSP code from a conference to learn Rust generics. I'm having trouble with E0283 - I want the compiler to infer a type but I don't think my trait implementations ...
2
votes
1
answer
97
views
Rust display trait performs poorly compared to `serde::serialize`
I've implemented a Rust clone of bgpdump that displays MRT messages in the same format as bgpdump. To print the message, I implemented the Display trait and printed it to stdout. However, I'm ...
4
votes
1
answer
164
views
How do I stub out an impl Trait-returning function?
If I have a function that I haven't yet had time to implement while I'm working on its higher-leve callers, I can stub it out with a panic:
fn foo() -> u64 {
panic!("TODO");
}
However, ...
-3
votes
1
answer
102
views
Using generics together with async, cannot find method of struct
I am implementing a function in Rust that take a callback function as an argument. As far as I learned, I can use Fn trait bound to do that.
But now I want this callback function to be async, and I ...
0
votes
1
answer
88
views
Can Rust create more restricted supertraits?
I'm trying to recreate a quantum API that I previously wrote in Python, in Rust now. I don't want to confuse anyone with quanum stuff, so I've tried to make the question more generic.
Lets say we want ...
0
votes
1
answer
76
views
Idiomatic solution to enforce trait bounds
So I have a struct WeatherStation which consists of a name: String and probability distribution function which should implement the rand::distr::Distribution trait. It look something like this:
struct ...
7
votes
3
answers
246
views
Can Rust const generics use trait bounds with an inequality (e.g. N2 > N1)?
I'm working on a project where I'm building a bit vector type in Rust, and I'm exploring whether it's possible to constrain const generics using inequality bounds.
My goal is to design an API that ...
2
votes
1
answer
92
views
Function objects with arguments that extend a trait
I have the following code. The compiler complains about the last line. I am wondering why. The WrappedFunction case class takes a function object with trait arguments. When I try to construct a ...
1
vote
0
answers
49
views
In Rust, can I blanket-implement a supertrait on types that attempt to implement one of its subtraits? [duplicate]
In present Rust, code like the following compiles and runs without error:
trait Trait1: Trait2 {}
trait Trait2 {}
impl<T: Trait1> Trait2 for T {}
impl<T> Trait1 for T {}
fn main() {
...
0
votes
0
answers
63
views
Which trait bound should be specified to mean "any selectable table" in Diesel ORM?
When writing a function that should be able to operate on any Diesel selectable table, for example something like "is this table empty", what is the correct way to specify the trait bound?
I ...
3
votes
1
answer
101
views
Why are these two trait implementations not conflicting?
I have a situation in my codebase where i have one function which has a boxed trait object calling a function which expects an implementor of that trait, and i got the error message shown below. For ...
0
votes
1
answer
87
views
How can I make a trait that allows conversion between all types implementing it?
I'm writing a library that deals with numerical attributes. For this I have created a trait for all the number primitives:
trait Sealed {}
#[allow(private_bounds, reason = "To seal trait Number&...
5
votes
1
answer
109
views
`T: Trait`/`impl Trait` doesn't satisfy `dyn Trait`, except when it does
I've encountered a strange variance behavior that I'm sure is a hole in my understanding of the type system, but feels like a compiler bug.
trait Trait: 'static {}
impl<T> Trait for T where T: '...
1
vote
1
answer
160
views
Why use Rust traits for "implementing shared behavior" if each object with the same trait still needs its own implementation written?
Reading the Rust book and struggling to understand why I should use traits over methods if I still need to write an implementation of the trait for each object that can have that trait.
Apart from the ...
2
votes
1
answer
98
views
What's the difference between `T: Trait + 'a` and `impl Trait + 'a` in Rust?
I originally thought T: 'a will restrict you form using T instance outside 'a because this exmaple reports an error:
fn main() {
let num;
{
let num1 = 10; // error: num1 doesn't live ...
1
vote
0
answers
57
views
How do I make traits share conflicting methods and properties in PHP
I have this trait
HasExtendedRoles.php
trait HasExtendedRoles
{
use HasRoles;
use HasExtendedPermissions {
HasExtendedPermissions::getPermissionClass insteadof HasRoles;
...
0
votes
1
answer
139
views
Return a custom error from enum FromStr parsing
I am implementing FromStr for my custom enum.
I need to prompt the user for the option, so I need to convert it to string (done via fmt::Display), and then when the user selects the option from the ...
5
votes
2
answers
164
views
Trying to make bounded floating point types in rust, problem with From and Into
Here is the code, I'm trying to make bounded floating point numbers.
I do this with a Bounds trait, that must be implemented for the generic type B in the Bounded number struct.
I would like to be ...
1
vote
1
answer
53
views
Generic trait not implemented for a closure returned by a function
I've been trying to reimplement the nom crate (for learning about parsing) and I cannot figure out how to implement a trait for a closure returned by a function.
The trait
The trait is meant to be ...
0
votes
1
answer
90
views
How to write test for Trait
I have a Trait called HasDefault
its main purpose is to ensure that the class has a static field $default which is callable and returns the default instance of the class using the Trait
This is what ...
0
votes
1
answer
36
views
Define trait as supertype of existing built-in type
How do I say „Here's a trait Lookup with a get(key: String): Option[V] method which Map[String, V] already happens to implement”?
I tried
trait Lookup[V] {
def get(key: String): Option[V]
}
but ...
0
votes
0
answers
19
views
Using generic constants and AsRef in operator overloading [duplicate]
So, at the moment, I'm implementing a matrix. This
fn multiply<const P: usize, T>(&self, rhs: T) -> Matrix<R, P>
where
T: AsRef<Matrix<C, P>>,
is the signature of ...
0
votes
1
answer
56
views
How to make a trait that uses an array whose length changes with each implementer? [duplicate]
I have a trait that specifies a deserialization function for its implementor. This trait should take in a fixed size array of u8 where the length of this array depends on the implementer (e.g. type A ...
1
vote
1
answer
1k
views
Axum the trait Handler<_, _, _> is not implemented for fn item [duplicate]
While implementing a handler function for an Axum endpoint, I ran accross the following error
--> qubic-rpc/src/lib.rs:90:38
|
90 | .route("/balances/{id}", get(routes::...
0
votes
1
answer
43
views
Implement foreign Trait with Implicit lifetime on method
I have following foreign trait I don't control:
pub trait Foo<T> {
fn foo(input: &T) -> Self;
}
I want to implement that trait for a reference of an unsized Type that lives ...
0
votes
1
answer
53
views
How to unify error types for Sender::send and JoinHandle::join?
The signatures for Sender::send and JoinHandle::join are, respectively:
pub fn send(&self, t: T) -> Result<(), SendError<T>>
pub fn join(self) -> Result<T, Box<dyn Any + ...
0
votes
1
answer
184
views
Problem with method visibility in a trait in Rust [closed]
I'm working on a Rust project and have a trait called Auth with an asynchronous method auth_login. The issue I'm facing is that when I try to make the method accessible from other modules using pub, I ...
5
votes
1
answer
66
views
Overflow when checking trait bound on a custom Add implementation
I'm trying to make a zero cost abstraction library that adds units to values, to ensure computations homogeneity at compile time.
The core type is:
pub struct QuantifiedValue<T, U: Unit> {
...
1
vote
1
answer
54
views
Expose function and trait that hides internal trait bounds
Goal
I am attempting to provide a generic function which will generate a list of random floats from the standard normal distribution. In particular, I am using the rand and rand_distr crates to do the ...
0
votes
1
answer
46
views
Implementing std::ops::Add for arguments with disimilar types [closed]
I want to create types, and implementations of std::ops::Add such that:
add(Position, Displacement) -> Position
add(Displacement, Displacement) -> Displacement
The purpose is to make nonsense ...
0
votes
0
answers
81
views
VSC PHP Intelephense not see class trait in Controller
Latest Laravel with PHP 8.3 and intelephense plugin for autocomplete in VSC.
If I using a method from a Model class Trait like createToken() in a User Model that using tokens, but the autocomplete is ...
0
votes
0
answers
76
views
Trait with blank constraint on lifetime
This code (derived from a more complex example) compiles [playground]:
fn func1<'a>(s: &'a str) where 'static: 'a { println!("{s}"); }
fn func2<'a>(s: &'a str) { func1(s)...
3
votes
1
answer
76
views
Generic Trait Parameters in Rust
I have a custom smart pointer which I'm trying to extend to trait objects. Essentially what I'm trying to make is the following:
use std::ptr::NonNull;
struct Ptr<T: ?Sized> {
data: NonNull&...
1
vote
1
answer
50
views
I have extended a type with a trait, why is my Vec<impl ThatTrait> not accepting a type that implements that trait? [duplicate]
I have a trait Input that adds a to_custom_bytes() method to Strings and u64s.
trait Input {
fn to_custom_bytes(&self) -> Vec<u8>;
}
impl Input for u64 {
fn to_custom_bytes(&...
1
vote
1
answer
87
views
Difference between declarations of trait bounds
I'm building myself a parsing library, and I found a key distinction between two types of declared trait bounds.
Take the following trait:
pub trait Parsable: FromStr<Err: Display>
{}
With this,...
0
votes
3
answers
168
views
Can you emulate rust's Fn trait using type classes?
In Rust, there is no type for functions, but rather an Fn trait that looks something like this:
trait Fn<A: Tuple, R> {
fn call(self, args: A) -> R;
}
Then the type of a function can be ...
0
votes
1
answer
69
views
Implement a trait for multiple generic traits
I'm trying to implement a trait for Display and Debug traits, but rust responds with conflicting implementations.
Here is my code:
pub trait AsString {
fn as_string(self) -> String;
}
impl<...
1
vote
0
answers
40
views
Recursive traits for flattening multidimensional vectors
Suppose I we want to flatten vectors:
[0, 50, 100] -> [0, 50, 100]
[[0], [50, 50], 100] -> [0, 50, 50, 100]
[[[0]]] -> [0]
We can define a trait such as
pub trait FlattenVec<A> {
...
0
votes
0
answers
49
views
How to resolve possibly conflicting recursive Rust trait implementations?
With the following code, I am able to add functionality to existing types:
pub trait Action<RHS> {
fn action(self, rhs: RHS) -> Self;
}
impl Action<i8> for u8 {
fn action(self, ...
2
votes
1
answer
159
views
Why can't you implement an impl Trait type in rust
Say that I have the following trait:
trait SayHello {
fn say_hello(self) -> String;
}
Why can I then do this:
fn say_hello_twice(this: impl SayHello) -> String {
let said_hello = this....
1
vote
1
answer
86
views
Take default value if not present
Have trait like below
trait MyTrait
{
val country: String,
val state: String,
val commune: String = "nothing"
}
Now implementing MyTrait
case class ImplementTrait(
...