0

I'm trying to implement Knuth's Algorithm X but I'm having trouble with generating the linked list. My column headers and data points are different types, but similar in build.

type ListObject interface{}

type Data struct {
    L, R, U, D, C *ListObject
}

type Column struct {
    L, R, U, D, C *ListObject
    Size          int
    Name          string
}

and this is the very WIP code, where i encountered the problem:

func CreateLinkedList(sparceMatrix [][]int) Column {
    masterHeader := new(Column)
    currentHeader := masterHeader
    for i, col := range sparceMatrix[0] {
    }
    currentHeader.R = masterHeader

    return masterHeader
}

The bit the compiler dislikes is the currentHeader.R = masterHeader bit.

The variables in the Data struct are adjacent dada structs (Left, Right), but U(p) and D(own) could also be a Column object.

I thought about using a interface for a ListObject struct, as you an see, but the compiler does not like that. Other than that, i haven gotten a good idea to the solution. Worse case scenario, i have to make every struct in the list the same type.

Any advice would be appreciated, new to programming.

Erik
  • 11
  • 1
    Make data and columns the same type. Use https://medium.com/@reetas/clean-ways-of-adding-new-optional-fields-to-a-golang-struct-99ae2fe9719d to make size and name optional. Have default values on size and name that clearly indicate that data is not a header. Now it is easy to make your linked list with both data and columns together. – btilly Apr 05 '23 at 19:57

1 Answers1

0

First and foremost, pointer to interface (like *ListObject) is practically never what you want. That is the cause of your error cannot use masterHeader (variable of type *Column) as *ListObject value in assignment: *Column does not implement *ListObject (type *ListObject is pointer to interface, not interface). Change every instance of *ListObject to ListObject and everything will go more smoothly.

The other error is cannot use masterHeader (variable of type *Column) as Column value in return statement, which is just as it says; you're creating a *Column (pointer to column), but your function signature says you're returning a Column. Likely you want to change the function signature to return *Column here.

Adrian
  • 42,911
  • 6
  • 107
  • 99
  • But the list object that im recording, that can still be a pointer then? – Erik Apr 05 '23 at 20:27
  • Yes, the value inside the interface can be a pointer. – Adrian Apr 05 '23 at 20:28
  • this seemed to work for that error. I now have a problem of not being able to access the fields in a loop (interface has no field or method). so it seems im back to square one :D if you got any suggestions for that, id take them :D but thank you anyway – Erik Apr 06 '23 at 11:49
  • You could give your interface methods and use them for navigating the linked list instead of direct field access. – Adrian Apr 06 '23 at 14:04