Menu
  • HOME
  • TAGS

“conflicting implementations for trait” when trying to be generic

Tag: types,rust

Background: I'm using the nalgebra library and I want to create a structure that represents a multivariate normal distribution. M is the type of the matrix, e.g. Mat4<f64>.

My current attempt looks like this:

use std::ops::Mul;
use std::marker::PhantomData;
use nalgebra::*;

#[allow(non_snake_case)]
pub struct Multivar𝒩<N, V, M: SquareMat<N, V>> {
    μ: V,
    Σ: M,
    marker: PhantomData<N>
}

impl<N, V, M> Mul<Multivar𝒩<N, V, M>> for M {
    type Output = Multivar𝒩<N, V, M>;
    fn mul(self, rhs: Multivar𝒩<N, V, M>) -> Multivar𝒩<N, V, M> {
        Multivar𝒩 {
            μ: self * rhs.μ,
            Σ: self * rhs.Σ * transpose(&self)
        }
    }
}

However, the compiler complains with:

error: type parameter `M` must be used as the type parameter for some local type (e.g. `MyStruct<T>`); only traits defined in the current crate can be implemented for a type parameter

and

error: conflicting implementations for trait `core::ops::Mul`

I don't believe this should be an error since I'm defining an implementation for a struct I have defined in this module. How shou

Best How To :

The problem with your code is that you have a coherence violation in it, and, very likely, any attempts to fix it would lead to new coherence violations.

Coherence rules in Rust are somewhat complex, however, they are based on one principle: you can implement "your" traits for arbitrary types and you can implement arbitrary types for "your" types. It sounds simple, but it becomes complicated when type parameters come into picture - it turns out that there are more than one ways to define which types are "yours" and which are not.

In this particular case the error is in that you're implementing a foreign trait for a type parameter directly:

impl<N, V, M> Mul<Multivar𝒩<N, V, M>> for M

This directly violates the above principle - you can't implement traits you don't own for types you don't own (such implementations are called "orphan impls"). This is exactly what your first error is about.

The second error makes me think that you have more Mul implementations than you provided here; anyway, it is also a coherence violation. Typically such error is caused when you have intersections of sets of types applicable for two or more different implementations of a trait:

use std::fmt;

trait X {}

impl X for i32 {}
impl<T: fmt::Display> X for T {}

Here implementations are conflicting because they both are applicable for i32 because i32 implements fmt::Display.

In fact, it is difficult to tell what you want, so it is also difficult to give a satisfying answer. I tried to explain the reason for these errors above, hopefully it would help you to write trait implementations properly. If you're interested, you can find more in this blog post on orphan rules.<

C# - Get all types that been used in class A

c#,reflection,types

[MyAttribute(new OtherType(TestEnum.EnumValue1))] That's not valid, you have to have a constant in attribute constructors. That matter aside, most of this is easy, if rather long-winded. You can call typeof(MyClass).CustomAttributes.Select(ca => ca.AttributeType) to get the types of attributes, typeof(MyClass).GetFields().Select(fi => fi.FieldType) to get the types of fields, and so on. Union...

Unconstrained type parameters casting

c#,.net,types,casting

The compiler sees the T2 and T identifiers and helpfully informs you that those types seem unrelated. That's absolutely correct, as they have no relation: there are no generic constraints that would assert any relations between them (I'm not saying that would be useful here though :) ). Whether this...

cannot move out of borrowed content - ref doesn't work [duplicate]

rust

Short answer The function fn2 receives a reference to a MyEnum1 as a parameter, but the Struct1 contains an owned MyEnum1. This means that you are actually trying to turn a reference into an owned value, which is only possible if you copy the data. Long answer Your code would...

Why Comparison Of two Integer using == sometimes works and sometimes not? [duplicate]

java,types,comparison

The Java Language Specification says that the wrapper objects for at least -128 to 127 are cached and reused by Integer.valueOf(), which is implicitly used by the autoboxing.

Create shared C object linked to Rust dylib for use in R

c++,c,r,rust,ffi

In the C++ code, you need to declare the Rust function (which is available via the C ABI) as extern "C". treble.h #include <stdint.h> extern "C" { int32_t treble(int32_t value); } The error you are getting is because the C++ compiler is name mangling the method treble before attempting to...

Filter vector in place

iterator,rust

If you want to remove elements you can use retain(), which removes elements from the vector if the filter function return false: let mut vec = vec![1, 2, 3, 4]; vec.retain(|&x| x%2 == 0); assert_eq!(vec, [2, 4]); If you want to modify the elements in place there is map_in_place() but...

Pass Python list to Rust function

python,rust,ffi

Looks like I solved the problem. I turned the Python list into a C array, and passed that to the Rust function. Here is the working code: #[repr(C)] pub struct List_4 { // Create a struct using #[repr(C)], will do the same in Python so it is shareable array: [i32;...

What is the most appropriate way to convert nibbles to a u64?

rust

Your issue is a simple one: for i in values, where values is of type &Vec<u8>, iterates over references to each value; that is, i is of type &u8. Oring and adding and such with references doesn’t make sense; you need to dereference it, getting the underlying u8. The easiest...

Why do I have to expose a macro implementation's 'use' in the client library?

macros,rust

Because macro_rules! is a bit dumber than you might expect. It does not, for example, bring imports with it when it expands something. It's best to think of macro expansion as mostly just a dumb copy+paste job. If you look at any reasonably well-written macro that depends on outside symbols,...

Return a moving window of elements resulting from an iterator of Vec

iterator,rust

You can use Vec::retain instead of filter for this, which allows you to keep your Vec: fn main() { let mut buf = vec![ 8, 9, 10, 11, 12, 13, 14, 8, 9, 10, 11, 12, 13, 14, 8, 9, 10, 11, 12, 13, 14, ]; println!("{:?}", buf); buf.retain(|&x| x...

Bug in FFI when passing CString followed by an int

windows,rust,32-bit,ffi

It seems that the 2nd arg is being interpreted (either in rust or c) as sizeof string, rather than the value passed from the Rust code. Correct. You are experiencing undefined behavior here. Your C-Function has a different signature from the extern function you declared in Rust-Code. First of...

Why do I need to use self::core::ops?

rust

An extern crate x; loads x into the current namespace. use statements are absolute paths unless they start with self::, so if you put your extern crate core; anywhere but the crate root then you need to specify an absolute path or use self::. mod foo { mod bar {...

How can I open a file with the standard text editor?

rust

You can use the open crate. It supports Windows, OS X and Linux. To open a text-file on your C: drive, you can use extern crate open; fn main() { open::that("C:\textfile.txt"); } ...

Value does not live long enough when using multiple threads

rust

The error does look misleading, however, it is correct. Your problem in fact is that chunks() gives an iterator of slices into the original vector, and because you're trying to use this slice in a spawn()ed thread, it must have 'static lifetime, but naturally it does not. You said that...

Load a shared library linked to Rust library in R

r,shared-libraries,rust

The problem is going to boil down to the fact that your shared libraries are not in the directories that your system expects them to be by default. There are a few tricks that you can use, 2 of which I was able to make work: Run R from the...

Indexing a String

rust

Indeed, the size of a [u8] isn't known at compile time. The size of &[u8] however is known at compile time because it's just a pointer plus a usize representing the length of sequence. format!("{:?}/{:?}", &bytes[0..2], &bytes[2..4]) Rust strings are encoded in utf-8, so working with strings in this way...

Conditionally compile only one module at a time

rust

You can run tests specifically for one module by providing it as an argument to the test binary. Cargo passes arguments to the test binary if you specify it after --, so something like this should work: cargo test -- module::you::want::to::test However, you can't compile only a part of a...

Reading immutable value inside spawned thread

rust

You're almost there. It's just that Arc has to be cloned outside of the spawned thread: for chunk in chunks { let thread_tx = tx.clone(); let user_index_cloned = user_index.clone(); thread::spawn(move || { let result = chunk.iter().map( |row| User { reference: row[user_index_cloned.reference].to_string(), email: row[user_index_cloned.email].to_string() } ).collect::<Vec<User>>(); thread_tx.send(result).unwrap(); }); } This has...

Casting to a generic type

rust

You simply have to specify T::Output as the return type of the function: fn divide<T: std::ops::Div>(a: T, b: T) -> T::Output { a / b } Edit to add more explanation on why you cannot do the cast inside the function When you are IN your generic function divide, the...

Writing Vec to a file

rust

To do it directly you'd want to use std::slice::from_raw_parts() function: use std::slice; use std::mem; fn main() { let slice_u16: &[u16] = &*vec![1, 2, 3, 4, 5, 6]; println!("u16s: {:?}", slice_u16); let slice_u8: &[u8] = unsafe { slice::from_raw_parts( slice_u16.as_ptr() as *const u8, slice_u16.len() * mem::size_of::<u16>() ) }; println!("u8s: {:?}", slice_u8); }...

How can I create Haskell-like functional dependencies

rust

While Haskell has two things to express such relationship between types, fundeps and associated types, Rust has only the latter. Traits in Rust can contain type members which are assigned with concrete values at the implementation site, and the compiler considers them uniquely identified by the combination of type parameters...

Can Rust handle cyclic data structures without any garbage collector?

rust

As for the title question - Yes, cyclic data structures can be handled without garbage collector. http://smallcultfollowing.com/babysteps/blog/2015/04/06/modeling-graphs-in-rust-using-vector-indices/ http://featherweightmusings.blogspot.com/2015/04/graphs-in-rust.html For first question. Yes, you can completely avoid garbage collector and manual deallocation in most cases. In some you rely on RC which is a simple form of garbage collection, or unsafe,...

Can I create a macro that unrolls loops?

macros,rust

Well, sort of. macro_rules! unroll { (0, |$i:ident| $s:stmt) => {}; (1, |$i:ident| $s:stmt) => {{ let $i: usize = 0; $s; }}; (2, |$i:ident| $s:stmt) => {{ unroll!(1, |$i| $s); let $i: usize = 1; $s; }}; (3, |$i:ident| $s:stmt) => {{ unroll!(2, |$i| $s); let $i: usize =...

Create a vector from iterating hashmap

rust

Your resulting Vec needs to own the Strings, so remove the & before the user.reference.clone(). Playground URL: https://play.rust-lang.org/?gist=6a6b50ebf589fcce1dbf&version=nightly Gist URL: https://gist.github.com/6a6b50ebf589fcce1dbf...

What is the idiomatic way to write a linked list with a tail pointer?

linked-list,rust,reference-counting

Yes, if you want to write a singly-linked-list with a tail-pointer you have three choices: Safe and Mutable: Use NodePtr = Option<Rc<RefCell<Node<T>>>> Safe and Immutable: Use NodePtr = Option<Rc<Node<T>>> Unsafe and Mutable: Use tail: *mut Node<T> The *mut is going to be more efficient, and it's not like the Rc...

How can I express foldr in terms of foldMap for type-aligned sequences?

haskell,types,monoids,type-variables,foldable

I found that this typechecks: {-# LANGUAGE RankNTypes #-} module FoldableTA where import Control.Category import Prelude hiding (id, (.)) class FoldableTA fm where foldMapTA :: Category h => (forall b c . a b c -> h b c) -> fm a b d -> h b d foldrTA ::...

vector method push_all is not found for a custom struct

rust

Look at the definition of push_all: impl<T> Vec<T> where T: Clone { fn push_all(&mut self, other: &[T]); } Appends all elements in a slice to the Vec. Iterates over the slice other, clones each element, and then appends it to this Vec. The other vector is traversed in-order. (Emphasis mine.)...

“conflicting implementations for trait” when trying to be generic

types,rust

The problem with your code is that you have a coherence violation in it, and, very likely, any attempts to fix it would lead to new coherence violations. Coherence rules in Rust are somewhat complex, however, they are based on one principle: you can implement "your" traits for arbitrary types...

SPARQL: How do I List and count each data type in an RDF dataset?

types,count,sparql

Since you've grouped by the datatype of ?o, you know that all the ?o values in a group have the same datatype. You can just sample that to get one of those values, and then take the datatype of it: select (datatype(sample(?o)) as ?datatype) (count(?o) AS ?dTypeCount) where { ?s...

why (int) ( 307.03 * 100) = 30702 [duplicate]

php,types,floating-point,int

The float val is stored as 307.02999 or something like that intval just truncate the number, no rounding, hence 30702.

Why does Drop take &mut self instead of self?

rust

Let's look at how std::mem::drop is implemented: pub fn drop<T>(_x: T) { } That's right: it's an empty function! That's because it takes advantage of move semantics to acquire ownership of its argument. If T implements Drop, the compiler automatically inserts a call to Drop::drop(_x) at the end of the...

remove duplicates from vector of custom struct

rust

If you look at the documentation for Vec::dedup, you'll note that it's in a little section marked by the following: impl<T: PartialEq> Vec<T> This means that the methods below it exist only when the given constraints are satisfied. In this case, dedup isn't there because User doesn't implement the PartialEq...

Implement Debug trait for large array type

rust,traits

use std::fmt; struct Array<T> { data: [T; 1024] } impl<T: fmt::Debug> fmt::Debug for Array<T> { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { self.data[..].fmt(formatter) } } fn main() { let array = Array { data: [0u8; 1024] }; println!("{:?}", array); } It's not possible to implement Debug for [T; 1024]...

the type of this value must be known in this context

rust

On an iterator, the collect method can produce many types of collections: Vec, String and many more. You cannot call the method len() on a value of an unknown type. Specify the type with something like .collect::<Vec<_>>(). Or, when you’re purely wanting to find out how many items there are...

Rust: Lifetime of String from file [duplicate]

file,io,rust

The string bound to "s" will be deallocated once the function ends ("s" goes out of scope), so you cannot return a reference to its contents outside the function. The best way is to return the string itself: fn read_shader_code(string_path: &str) -> String { let path = Path::new(string_path); let display...

How to use multiple variables in routes with Nickel?

rust,nickel

You need a separator. For example: #[macro_use] extern crate nickel; use nickel::Nickel; fn main() { let mut server = Nickel::new(); server.utilize(router! { get "/start/:userid/:passwd" => |request, _response| { println!("this is user: {:?} = {:?}", request.param("userid"), request.param("passwd") ); "Hello world!" } }); server.listen("127.0.0.1:6767"); } It looks from your question like you...

Immutable reference after mutable borrow

rust

Your program panics because you're trying to borrow the Vec mutably and immutably at the same time: this is not allowed. What you need to do instead is wrap only the Strings in RefCell. This allows you to mutate the strings while iterating the Vec. use std::cell::RefCell; struct Res {...

Struct vs enum lifetime differences

rust,lifetime

To me it seems like let c = Bar::Fub(&17), the 17 lasts the same life time as the previous line where "Foo" is created on the stack A string literal always has 'static lifetime and will therefor always live long enough. I think the issue is that you are...

Why is `Sized` bound necessary in this trait?

rust,traits

As you probably already know, types in Rust can be sized and unsized. Unsized types, as their name suggest, do not have a size required to store values of this type which is known to the compiler. For example, [u32] is an unsized array of u32s; because the number of...

int* const* foo(int x); is a valid C function prototype. How do you “read” this return type?

c++,c,types,grammar

The return type is a pointer to const pointer to int. Read the declaration from right to left, and it will make things much easier. My favourite tutorial for complicated pointer declarations: http://c-faq.com/decl/spiral.anderson.html Some (quite artificial) example: #include <iostream> int* const * foo(int x) { static int* const p =...

Lifetime of a mutable element in struct

rust

I know this has been answered before, but I can't find it... feel free to mark this as duplicate if you find it. The problem is that you are attempting to store a reference in a container that will outlive the reference. Here's a MCVE of your problem: fn main()...

More convenient way to work with strings in winapi calls

string,winapi,rust

In your situation, you always want a maximum of 255 bytes, so you can use an array instead of a vector. This reduces the entire boilerplate to a mem::uninitialized() call, an as_mut_ptr() call and a slicing operation. unsafe { let mut v: [u16; 255] = mem::uninitialized(); let read_len = user32::GetWindowTextW(...

Implementing a generic conversion from an object implementing the `Error` trait

rust

You don't. That implementation would be a bit useless, anyway. It would mean that all other error types would just be immediately boxed. At that point, you might as well just make use of the existing conversions involving Box<Error> and use that instead. If you want an error type that...

Best practice for handling data types from 3rd party libraries in Haskell?

haskell,types

I am not ready to give a nice list of best practises, but for starters if you want to keep stuff sanely organized, use explicit exports instead of just exporting everything, e.g: module Parser ( parseConfig ) where ... Explicit exports also allow you to reexport your imports, e.g. module...

Javadoc: Do parameter and return need an explicit type description

java,types,javadoc

No, there's no need, the JavaDoc tool parses the Java code and gets the types from there. This article on the Oracle Java site may be useful: How to Write Doc Comments for the Javadoc Tool From the @param part of that article: The @param tag is followed by the...

Result has no method called “unwrap()”?

rust

If you read the documentation for Result::unwrap, you'll note that it's under a little section called: impl<T, E: Debug> Result<T, E> This means the methods in that section only exist so long as the given constraints are satisfied. So far as I can see, the only reason unwrap wouldn't exist...

Cannot infer appropriate lifetime for autoderef in Iterator impl

rust

You need to update your get method to return a reference with longer life: // Use 'a from impl<'a> IntegerArrayBag<'a> fn get(&self, idx: usize) -> Option<&'a i32> { and then it will compile....

How can I send a function to another thread?

multithreading,unit-testing,rust

There are several problems with your code, I'll show you how to fix them one by one. The first problem is that you're using map() to iterate over an iterator. It won't work correctly because map() is lazy - unless you consume the iterator, the closure you passed to it...

Renaming a crate with a hyphen doesn't compile anymore

rust

Dashes in extern crate names can be replaced with underscores. So your example should be extern crate my_crate as my_crate1; Or if you want the underscored name, using the following will work extern crate my_crate; ...