Home > database >  invalid operation: room != g.End (mismatched types string and *Room)
invalid operation: room != g.End (mismatched types string and *Room)

Time:05-14

Here is my struct :

type Graph struct {
    rooms     []*Room
    Start     *Room
    End       *Room
    adjacents map[string][]string
}

type Room struct {
    name     string
    visited  bool
    occupied bool
}

var (
    Task    string
    visited = make(map[string]bool)
    path    = []string{}

    // all paths found
    Paths = [][]string{}
)

// implements DFS algorithm to find all paths from start to end rooms

func (g *Graph) Dfs(room string) {
    if visited[room] {
        return
    }
    visited[room] = true
    path = append(path, room)
    if room != g.End {
        for _, neighbour := range g.adjacents[room] {
            g.Dfs(neighbour)
        }
    } else {
        copy := make([]string, len(path))
        for i, v := range path {
            copy[i] = v
        }
        Paths = append(Paths, copy)
    }
    path = path[:len(path)-1]
    visited[room] = false
}

it is complaining on the 2nd if statement that 'room' is mismatched types before it ranges through the adjacent rooms. I know theres an issue, but cant seem to figure this out

CodePudding user response:

Your types are mismatched. room is of type string while g.End if a pointer to type Room. Instead of if room != g.End try if room != g.End.name

CodePudding user response:

room != g.End is not possible because room is string and g.End is *Room, if room is the room name you can use g.End.name to make the comparison,room != g.End.name

however it will depend on whether Room is in the same package as Dfs so that it can access the name property

  •  Tags:  
  • go
  • Related