Only traits defined in the current crate can be implemented for arbitrary types

I want to implement Serialize on Vec<u8>, but got an error:

Only traits defined in the current crate can be implemented for arbitrary types

Could somebody explain if there any good solution for this except defining my own type:

struct MyVec(Vec<u8>);
impl Serialize for MyVec { ... }

That's pretty much the recommendation in the general case, yeah. You can implement extra traits to make this less disruptive, in particular Deref/Mut let's you call Vec methods.

In the specific case of serde, though, you can also use #[serde(remote)], though it does require additional annotations on the use sites.

1 Like

It's also important to note that Vec<T> already implements Serialize whenever T does, so you need to wrap it into a new type or add some annotation if you want to override the default behaviour of just serialising every element in a collection.

2 Likes

And, to complete the line of reasoning, u8 also implements Serialize, so this case isn’t just a forward-compatibility issue: There’s already a working implementation of Serialize for Vec<u8> which would conflict with OP’s new implementation.

2 Likes

The solution is to use #[serde(serialize_with=...)]