# Creating "into operator"

**URL:** <https://internals.rust-lang.org/t/creating-into-operator/18137>\
**Category:** language design\
**Created:** [January 13, 2023, 9:13am UTC](https://internals.rust-lang.org/t/creating-into-operator/18137 "2023-01-13T09:13:23Z")\
**Posts on this page:** 16\
**Page:** 1

<div class="post-metadata">

**Author:** ![erikpa1](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/erikpa1/32/10408_2.png) [@erikpa1](https://internals.rust-lang.org/u/erikpa1)\
**Post date:** [January 13, 2023, 9:13am UTC](https://internals.rust-lang.org/t/creating-into-operator/18137/1 "2023-01-13T09:13:23Z")

</div>

Hi, I really like rust, sometimes writing of something is really long process and one of the idea I had is creating something like "into" operator to make less code (I know rust is safe, but small amount of code can be even safer,...).

for example

instead "my string".into() or String::from(), or f64::from

could be something like this:

- @"my string"
- @ \<u1 6\> 25

... and many more

![image](https://us1.discourse-cdn.com/flex002/uploads/rustlang/original/2X/7/77e319d2bc733aa4248feb7ee87bd26488b7d5bb.png)

 ![image](https://us1.discourse-cdn.com/flex002/uploads/rustlang/original/2X/8/83d5869f8269c0027054de13546c2e9398e77251.png)

---

<div class="post-metadata">

**Author:** ![canndrew](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/canndrew/32/1676_2.png) [@canndrew](https://internals.rust-lang.org/u/canndrew)\
**Post date:** [January 13, 2023, 12:09pm UTC](https://internals.rust-lang.org/t/creating-into-operator/18137/2 "2023-01-13T12:09:25Z")

</div>

Some opinions:

Rust generally favors explicit over implicit and `.into()` is already too easy to abuse. I've seen code that over-uses it to the point where it's impossible to figure out wtf is going on without digging deep into the APIs that are being called. I would much prefer people use more specific conversions wherever possible, eg. `.to_string()` instead of `.into()`, and for these methods to be added if they don't yet exist. So I really wouldn't like us to make changes which encourage people to (ab)use `.into()` even more.

Rust has a very high bar for adding new syntax. Using `@foo` vs `foo.into()` only saves 6 characters and I can't imagine the devs will consider that enough of an ergonomics improvement to justify adding a new operator.

While smaller code can be safer by being easier to read, more implicit code is often less safe since (a) you're relying on the compiler to correctly infer the intended types and (b) it's harder for the reader to know what the code is doing if the type information is omitted.

If you really want implicit conversions, a common pattern is to have constructor functions that take a generic `impl Into<T>`. eg.

```rust
struct Citizen {
    first_name: String,
    last_name: String,
}

impl Citizen {
    pub fn new(first_name: impl Into<String>, last_name: impl Into<String>) -> Citizen {
        Citizen {
            first_name: first_name.into(),
            last_name: last_name.into(),
        }
    }
}

citizen("John", "Smith")

```

Though without named function arguments these would (in your case) be easier to accidentally misuse compared to struct literals.

---

<div class="post-metadata">

**Author:** ![afetisov](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/afetisov/32/8508_2.png) [@afetisov](https://internals.rust-lang.org/u/afetisov)\
**Post date:** [January 13, 2023, 2:05pm UTC](https://internals.rust-lang.org/t/creating-into-operator/18137/3 "2023-01-13T14:05:44Z")

</div>

> [@erikpa1](#):
>
> small amount of code can be even safer

Let's just say it's highly debatable.

> [@erikpa1](#):
>
> @ \<u1 6\> 25

What the hell is this even supposed to mean?

The default disposition for any new operators in Rust is NO. Apart from the `?` operator, thus far no one has managed to convince otherwise.

---

<div class="post-metadata">

**Author:** ![Uther](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/uther/32/6225_2.png) [@Uther](https://internals.rust-lang.org/u/Uther)\
**Post date:** [January 14, 2023, 9:24am UTC](https://internals.rust-lang.org/t/creating-into-operator/18137/4 "2023-01-14T09:24:52Z")

</div>

> [@afetisov](#):
>
> What the hell is this even supposed to mean?

I guess it is supposed to mean

```
{ 
    let tmp: u16 = 25.into();
    tmp
}

```

or if type ascription is allowed everywhere one day:

```
25.into() : u16

```

---

<div class="post-metadata">

**Author:** ![Aloso](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/aloso/32/5039_2.png) [@Aloso](https://internals.rust-lang.org/u/Aloso)\
**Post date:** [January 23, 2023, 9:45pm UTC](https://internals.rust-lang.org/t/creating-into-operator/18137/5 "2023-01-23T21:45:30Z")

</div>

Note that type ascription has been [de-RFC'd](https://rust-lang.github.io/rfcs/3307-de-rfc-type-ascription.html) and most likely won't use this syntax if it is ever stabilized.

---

<div class="post-metadata">

**Author:** ![josh](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/josh/32/5934_2.png) [@josh](https://internals.rust-lang.org/u/josh)\
**Post date:** [January 24, 2023, 4:44am UTC](https://internals.rust-lang.org/t/creating-into-operator/18137/6 "2023-01-24T04:44:41Z")

</div>

I still think we should attempt to make `expr.into::<T>()` work the way people often expect it to.

---

<div class="post-metadata">

**Author:** ![jhpratt](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/jhpratt/32/11640_2.png) [@jhpratt](https://internals.rust-lang.org/u/jhpratt)\
**Post date:** [January 24, 2023, 6:23am UTC](https://internals.rust-lang.org/t/creating-into-operator/18137/7 "2023-01-24T06:23:39Z")

</div>

Agreed 100%. Doing so for `Into::into` could be hacked by making it a lang item. The problem is generalizing it to be able to provide the generics of the trait when calling a trait method.

---

<div class="post-metadata">

**Author:** ![steffahn](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/steffahn/32/13288_2.png) [@steffahn](https://internals.rust-lang.org/u/steffahn)\
**Post date:** [January 24, 2023, 6:34am UTC](https://internals.rust-lang.org/t/creating-into-operator/18137/8 "2023-01-24T06:34:01Z")

</div>

I feel like the trait method could simply opt into this behavior. Something like

```rust
pub trait Into<T>: Sized {
    fn into< =T >(self) -> T;
}

```

or some other syntax, specifying “here's another location for explicitly constraining / specifying the type `T`”.

For most trait methods, the types will be sufficiently constrained by the argument type or existing parameters already, so I don't think it's _necessary_ to come up with any approach that would automatically work with existing trait methods, because most trait methods would never need the syntax in the first place.

Adding such a `=T` parameter, which would be optional like other type parameters with a default, wouldn't be a breaking change, so any existing trait methods (including `Into::into`) could add support for this in minor releases.

---

<div class="post-metadata">

**Author:** ![jhpratt](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/jhpratt/32/11640_2.png) [@jhpratt](https://internals.rust-lang.org/u/jhpratt)\
**Post date:** [January 24, 2023, 10:54am UTC](https://internals.rust-lang.org/t/creating-into-operator/18137/9 "2023-01-24T10:54:27Z")

</div>

That could work. My immediate question is what if you did `Into::<T>::into::<U>(foo)` where T != U? Presumably a hard error for an ambiguous call? Syntax bikeshedding aside.

---

<div class="post-metadata">

**Author:** ![CAD97](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/cad97/32/3460_2.png) [@CAD97](https://internals.rust-lang.org/u/CAD97)\
**Post date:** [January 24, 2023, 11:09am UTC](https://internals.rust-lang.org/t/creating-into-operator/18137/10 "2023-01-24T11:09:39Z")

</div>

Whatever solution needs to be reasonably careful, since it's possible to call `expr.into::<>()` today. Any added generics need to be default inferred.

---

<div class="post-metadata">

**Author:** ![steffahn](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/steffahn/32/13288_2.png) [@steffahn](https://internals.rust-lang.org/u/steffahn)\
**Post date:** [January 24, 2023, 11:22am UTC](https://internals.rust-lang.org/t/creating-into-operator/18137/11 "2023-01-24T11:22:00Z")

</div>

> [@jhpratt](#):
>
> Presumably a hard error for an ambiguous call?

I’d say, either a conservative error ruling out the call syntactically already, or it would be a type mismatch. If the latter approach is chosen, something like `Into::<(Foo, _)>::into::<(_, Bar)>(baz)` would probably also be expected to _work_ and unify accordingly; same for redundantly specifying the type twice. Redundantly specifying types that are already inferrable is common in Rust anyways, e.g. for type signature on variables in many cases. Incorrectly specifying the type of a variable leads in a type mismatch error.

* * *

One somewhat comparable thing is how `enum` variants can get their arguments in two possible places. They seem to be using a _syntactical_ criterion.

```rust
let x: Option<()> = Option::None;
let x: Option<()> = Option::None::<>;
let x: Option<()> = Option::<>::None;
let x: Option<()> = Option::<>::None::<>;
let x: Option<()> = Option::<()>::None;
let x: Option<()> = Option::<()>::None::<>;
let x: Option<()> = Option::None::<()>;
let x: Option<()> = Option::<>::None::<()>; // fails
let x: Option<()> = Option::<()>::None::<()>; // fails

```

[Rust Playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=59fab9dade6050d25cb119017df94c38)

_Edit: Ah, didn't notice rustfmt “fixing” my test cases with empty_ `<>`_s. Fixed now._

---

<div class="post-metadata">

**Author:** ![steffahn](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/steffahn/32/13288_2.png) [@steffahn](https://internals.rust-lang.org/u/steffahn)\
**Post date:** [January 24, 2023, 11:46am UTC](https://internals.rust-lang.org/t/creating-into-operator/18137/13 "2023-01-24T11:46:44Z")

</div>

I just had written a lengthy response that was somewhat nonsensical, since I forgot that functions do _not_ support defaulted arguments in the first place 😅

I mean, perhaps it was not _completely_ nonsensical, since defaulted parameters are a reasonable future language addition, and we wouldn’t want to introduce any unnecessary extra complications for such a feature. The basic idea is that if the _trait parameters_ become implicitly added defaulted type parameters to trait methods, then adding normal defaulted parameters (if we get such a feature) would be a breaking change, since it mixes up the order. Well… or, if the order is different, then adding defaulted parameters to the _trait_ would be breaking. Problematic either way.

* * *

Indeed this feature would _add_ a first case where a function would have default arguments. There are no semantic questions as to how to handle those in this case though. Usually, the problem is that it’s unclear for functions when the defaults should actually be considered. In this case, the default _is_ to leave the parameter “inferred”. (It is _always_ unified with the trait’s parameter that it’s set to be equal to anyways.)

Makes me wonder: Are there existing proposals for adding something like

```rust
fn foo<S, T, U = _>() {}

```

i.e. type parameters whose default value is “leave this inferred”? Same argument as above, there would be no hard semantic questions to answer for such a feature. It would seem useful to me for making API such as [`Iterator::map`](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.map) nicer to call, since you wouldn’t need to specify the closure type anymore: `.map::<Ty, _>(|x| …)` (helps inferring the return type of the closure as `Ty`) would become somewhat neater, writable as `.map::<Ty>(|x| …)`.

It would also serve as a way of converting `impl Trait` parameters into named parameters without breakage.

---

<div class="post-metadata">

**Author:** ![elusian](https://avatars.discourse-cdn.com/v4/letter/e/c37758/32.png) [@elusian](https://internals.rust-lang.org/u/elusian)\
**Post date:** [January 24, 2023, 6:11pm UTC](https://internals.rust-lang.org/t/creating-into-operator/18137/14 "2023-01-24T18:11:38Z")

</div>

Apologies if this was already proposed, but would it make sense instead to have something like this?

```rust
trait IntoExt {
    fn to<Other>(self) -> Other where Self: Into<Other>;
}

impl<T> IntoExt for T {
    fn to<Other>(self) -> Other where Self: Into<Other> {
        Into::into(self)
    }
}

```

Generic bounds stay the same (you still require From/Into) but you'd be able to write

```rust
let n = 3u8;
let m = n.to::<u32>();

```

The trait would not be imported by default, but in a new epoch it could be added to the prelude.

Unfortunately the function cannot be called `IntoExt::into` because it conflicts with the existing `Into::into`

---

<div class="post-metadata">

**Author:** ![steffahn](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/steffahn/32/13288_2.png) [@steffahn](https://internals.rust-lang.org/u/steffahn)\
**Post date:** [January 24, 2023, 11:26pm UTC](https://internals.rust-lang.org/t/creating-into-operator/18137/15 "2023-01-24T23:26:37Z")

</div>

I actually published an implementation of such a trait some time ago as a crate.

> **[IntoExt in into\_ext - Rust](https://docs.rs/into_ext/latest/into_ext/trait.IntoExt.html)**
>
> Extension trait for the \[\`Into\`\] trait, offering a method \`.into\_::\<T\>()\` to specify the target type of conversion.

IIRC I've also seen other instances of similar traits in some utilities crates.

---

<div class="post-metadata">

**Author:** ![steffahn](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/steffahn/32/13288_2.png) [@steffahn](https://internals.rust-lang.org/u/steffahn)\
**Post date:** [January 24, 2023, 11:47pm UTC](https://internals.rust-lang.org/t/creating-into-operator/18137/16 "2023-01-24T23:47:47Z")

</div>

Fascinating stuff… looking back at my own crate, I’m noticing:

I use a signature of the form

```rust
fn into_<T>(self) -> T
where
    T: TypeIsEqual<To = T_>
{ … }

```

where `T: TypeIsEqual<To = T_>` is a library-implemented approximation to something like a `T == T_` bound.

So now I’m realizing that something like

```rust
trait Trait<T> {
    fn foo<S, =T>();
}

```

would be _equivalent_ to

```rust
trait Trait<T> {
    fn foo<S, T1 = _>()
    where
        T1 == T;
}

```

with proper `==` bounds, so that such a `=T` feature becomes redundant if we get `==` in `where` clauses as well as `= _` defaults.

Also, for methods with _previously no_ type arguments, the `= _` is kind-of redundant, since existing calls like

> [@CAD97](#):
>
> it's possible to call `expr.into::<>()` today

will not break, because `::<>` is [kind-of ignored by the compiler anyways](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=79d88485f0ed605a67f75a3ff8da7817).

* * *

I must say though that

```rust
trait Trait<T> {
    fn foo<S, T1 = _>()
    where
        T1 == T;
}

```

is IMO slightly more confusing to look at, as it involves a fully-fledged extra type argument and a constraint, whereas the interpretation of what this means is mostly for syntactical reasons/convenience; so even with this insight, `=T` could be a reasonable feature even if it’s just syntactic sugar.

---

<div class="post-metadata">

**Author:** ![system](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/system/32/14092_2.png) [@system](https://internals.rust-lang.org/u/system)\
**Post date:** [April 24, 2023, 11:48pm UTC](https://internals.rust-lang.org/t/creating-into-operator/18137/17 "2023-04-24T23:48:12Z")

</div>

Closed on April 24, 2023, 11:48pm UTC

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.
