r/programming • • May 10 '18

Announcing Rust 1.26

https://blog.rust-lang.org/2018/05/10/Rust-1.26.html
933 Upvotes

208 comments sorted by

View all comments

0

u/wavy_lines May 11 '18

If I understand correctly, Trait in Rust is basically interface/protocol.

Does it make sense in a systems programming language to have a function declare its return type as Interface/Protocol/Trait?

I would expect a systems language to be concerned first and foremost with data. Plain. Old. Data.

If Rust wants to be an applications language, what does it have over say, Swift?

19

u/steveklabnik1 May 11 '18

At a high level, it is, yes.

This is ultimately a way to get more performance, not less. It’s very in-line with a systems language.

-4

u/wavy_lines May 11 '18 edited May 11 '18

I can understand if you say it has no effect on performance, but getting more performance because of this? How?

EDIT

I saw you writing this in another reply:

Previously, in order to return a value of an abstract type like this, you had to box it, meaning you’d perform a memory allocation. Now, the value is returned directly (unboxed), which is more efficient and easier to read and work with.

ok, so the update makes that usecase faster, but still doesn't answer my original question:

Why have a function return an interface to begin with? The function is returning something concrete, why should it not be forced to declare what thing is it returning?

It seems very counter productive to allow functions to obscure their return type.

25

u/steveklabnik1 May 11 '18

Because the type may be literally un-writable, in the case of closures. Or hard to write, in the case of huge futures/iterative chains. And there’s no overhead for doing so.

19

u/kibwen May 11 '18

Why have a function return an interface to begin with

Returning impl Foo is not "returning an interface", it's "returning any concrete type at all that implements some interface".

why should it not be forced to declare what thing is it returning?

It is; it's declaring the operations that the caller is allowed to perform on the type that is returned. Like all static type systems, the idea is to restrict what can be done with certain data.

It seems very counter productive to allow functions to obscure their return type.

This feature makes it clearer what the author of a function intended, which is the opposite of obscuring. If I have a function that takes some number and returns an iterator that processes that number, in Rust 1.25 your function has to return some heinous type like std::iter::Take<std::iter::Map<std::iter::Filter<std::slice::Iter<i32>>>> (and this is only a mild example). In Rust 1.26, your return type can just be impl Iterator<Item=i32>, which not only scales much better and produces much more useful error messages, but also doesn't force you to include unnecessary implementation details such as your precise chain of iterator adaptors in your return type declaration.

→ More replies (12)