Skip to content

Returning Option<Self> in #[wasm_bindgen] impl block gives error  #3105

@filonik

Description

@filonik

Summary

This may not be the best example, but for simplicity I am adapting the code from this issue. The problem is as follows:

The following return types work for new with the #[wasm_bindgen] attribute applied to the impl: Universe, Self, Option<Universe>. However, this return type appears not to work: Option<Self>. Is there some deep reason for this, or is this potentially a bug?

extern crate wasm_bindgen;

use wasm_bindgen::prelude::*;

#[repr(u8)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Cell {
    Dead = 0,
    Alive = 1,
}

#[wasm_bindgen]
pub struct Universe {
    width: u32,
    height: u32,
    cells: Vec<Cell>,
}

/// Public methods, exported to JavaScript.
#[wasm_bindgen]
impl Universe {
    // The tutorial has the signature:
    // pub fn new() -> Universe {
    // This signature works:
    // pub fn new() -> Option<Universe> {
    pub fn new() -> Option<Self> {
        let width = 128;
        let height = 128;

        let cells = (0..width * height)
            .map(|i| {
                if i % 2 == 0 || i % 7 == 0 {
                    Cell::Alive
                } else {
                    Cell::Dead
                }
            })
            .collect();

        Some(Self {
            width,
            height,
            cells,
        })
    }
}

This gives the error:

error[E0401]: can't use generic parameters from outer function
   --> src\lib.rs:177:28
    |
139 | impl Universe {
    | ---- `Self` type implicitly declared here, by this `impl`
...
177 |     pub fn new() -> Option<Self> {
    |                            ^^^^
    |                            |
    |                            use of generic parameter from outer function
    |                            use a type here instead

The same problem arises when attempting to use Self with Result and other generics.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions