-2

So I'm making a little tictactoe to learn Rust. I define a Board which is a struct containing a 3 by 3 array called "tiles".

pub struct Board {
    pub tiles: [[Option<Players>; 3]; 3],
}

Then, I try to create a method that uses the element "tiles" as a parameter

impl Board {
    pub fn print_board (board: Board::tiles) {
}

However, Rust gets all offended and tells me this.

ambiguous associated typerustcE0223 game.rs(10, 32): use fully-qualified syntax: "<Board as Trait>::tiles"

First of all, I have no idea what this mean, but then I try to do as it says:

impl Board {
    pub fn print_board (board: <Board as Trait>::tiles) { 
}

it gives me squiggles under "Trait" where it says

failed to resolve: use of undeclared type "Trait" use of undeclared type "Trait"

Rust, o Rust what ever am I supposed to do?

Herohtar
  • 5,347
  • 4
  • 31
  • 41
Little A
  • 7
  • 1
  • 1
    why not make `print_board` an instance method called `print` instead? then It can access `&self` and by extension `self.tiles`, which is a property of an instance of `Board`. – rv.kvetch Apr 19 '22 at 13:41
  • you'd call it like `let board = Board{...}; board.print()` – rv.kvetch Apr 19 '22 at 13:42
  • Here `Trait` is meant as placeholder for some trait. For example, if `Board` implemented `Iterator`, you'd name the associated type `Item` as `::Item`. However, in this case you are *not* actually trying to access an associated type, so the suggestion is misleading. Rust doesn't have a typeof-style operator that would allow you to refer to the type of a struct field. – user4815162342 Apr 19 '22 at 17:29

1 Answers1

2

Board::tiles doesn't make syntactic sense. If board is a value of type Board, then board.tiles is a data member of the struct. Neither Board::tiles nor board.tiles is a type so you can't use it for defining the type of an argument.

You can either take the type of the data member explicitly, like this: pub fn print_board(board: [[Option<Players>; 3]; 3]).

Or if you don't want to write out that type again and again you can use a type alias like this

pub type TileArray = [[Option<Players>; 3]; 3];

pub struct Board {
    pub tiles: TileArray,
}

impl Board {
    pub fn print_board(board: TileArray) { 
        // ...
    }
}

The error message is confusing to you because you're specifying a type of a function parameter, but attempting to use the name of a value to do that. Your syntax is just completely invalid. The syntax SomeType::Something can make some sense, where Something is an associated type of some trait implemented by SomeType. This is the compiler's best guess of making sense of the syntax you gave it, so it's trying to correct you based on that. That syntax still wouldn't be correct, since you'd need the fully-qualified syntax indicated by the error message.

JMAA
  • 1,730
  • 13
  • 24