Skip to content

Can use + operator in broken and hilarious ways #15172

Closed
@tomjakubowski

Description

@tomjakubowski

(sorry about the bad title but I really have no clue what's going on here!)

use std::num::Num;

trait BrokenAdd: Num {
    fn broken_add<T>(&self, rhs: T) -> Self {
        *self + rhs
    }
}

impl<T: Num> BrokenAdd for T {}

pub fn main() {
    let foo: u8 = 0u8;
    let x: u8 = foo.broken_add("hello darkness my old friend".to_string());
    println!("{}", x);
}

Compiles and prints 28. I think it's getting at the len of the Vec inside a String.

edit: As one might expect, 0u8 + "hello darkness my old friend".to_string() does not compile.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions