How to specify return type in into() method

I tried this.

enum BlockType {
    I, O, T, J, L, S, Z
}

impl From<BlockType> for [(usize, usize); 4] {
    fn from(inp: BlockType) -> Self {
        match inp {
            BlockType::O => [(0, 0), (1, 0), (1, 1), (0, 1)],
            BlockType::I => [(0, 0), (0, 1), (0, 2), (0, 3)],
            BlockType::T => [(0, 0), (1, 0), (2, 0), (1, 1)],

            BlockType::Z => [(0, 0), (0, 1), (1, 1), (1, 2)],
            BlockType::S => (BlockType::Z.into() as [(usize, usize); 4]).map(|(x, y)| (y, x)),

            BlockType::L => [(0, 0), (0, 1), (0, 2), (1, 0)],
            BlockType::J => BlockType::S.into::<[(usize, usize); 4]>().map(|(x, y)| (y, x)),
        }
    }
}

This is not compiling.

How to specify return type in into()

The generic parameter of the .into() method is on the trait whence it originates, rather than on the method itself.

There are crates out there which feature helper / convenience extension traits which change that aspect, putting the generic parameter on the method, such as:

2 Likes
impl From<BlockType> for [(usize, usize); 4] {
..:     fn from(inp: BlockType) -> Self {
..:         match inp {
..:             BlockType::O => [(0, 0), (1, 0), (1, 1), (0, 1)],
..:             BlockType::I => [(0, 0), (0, 1), (0, 2), (0, 3)],
..:             BlockType::T => [(0, 0), (1, 0), (2, 0), (1, 1)],
..: 
..:             BlockType::Z => [(0, 0), (0, 1), (1, 1), (1, 2)],
..:             BlockType::S => {
..:                 let a: [(usize,usize);4] = BlockType::Z.into();
..:                 a.map(|(x, y)| (y, x))
..:             }
..:             BlockType::L => [(0, 0), (0, 1), (0, 2), (1, 0)],
..:             BlockType::J => {
..:                 let a:[(usize, usize); 4] = BlockType::S.into();
..:                 a.map(|(x, y)| (y, x))
..:                 }
..:         }
..:     }
..: }
..: }
1 Like

Also I didn't think about this but from the crate that @Yandros linked

Into::<[(usize,usize);4]>::into(BlockType::S).map(|(x, y)| (y, x))
1 Like

Hah, there's more of those kinds of traits out there than I thought / knew. I had semi-recently created my own crate offering such API

Though, one difference is that its approach only provides the method for types that actually implement Into.

(On second thought, all types implement T: Into<T>, so I guess that's an unnecessary optimization/complication; but it can be educational in how you could support passing generic arguments of the trait for other not-widely-implemented traits.)

2 Likes

Another option would be to use From rather than Into.

1 Like