-2

I'm new to golang and not sure if the question title is accurate, but I will try to add a better description for the problem.

In daos/model.go I have a package with the following code:

type ActionType int
const (
    ActionTypeExecute ActionType = 0 + iota
    ActionTypeSelect
    ActionTypeInput
    ActionTypeClick
    ActionTypeWait
)
func ActionTypeFromString(s *string) (ActionType, error) {
    switch *s {
    case "execute":
        return ActionTypeExecute, nil
    case "select":
        return ActionTypeSelect, nil
    case "input":
        return ActionTypeInput, nil
    case "click":
        return ActionTypeClick, nil
    case "wait":
        return ActionTypeWait, nil
    }
    return 0, ErrInvalidActionTypeText
}

The purpose of ActionTypeFromString is to convert a string passed as param to an int.

In actions/model.go I have another package:

type ActionType string
const (
    ActionTypeExecute ActionType = "execute"
    ActionTypeSelect ActionType = "select"
    ActionTypeInput ActionType = "input"
    ActionTypeClick ActionType = "click"
    ActionTypeWait ActionType = "wait"
)
type NewAction struct {
    ActionType *ActionType `json:"type"`
}

func insertActionsFromScan(newActions []*NewAction) {
    for _, newAction := range newActions {

        actionTypeInt, err := models.ActionTypeFromString(newAction.ActionType)
        if err != nil {
            return nil, err
        }
    }
}

Compiling the code gives the following error and I'm not understanding why, since newAction.ActionType is a string

cannot use newAction.ActionType (type *ActionType) as type *string in argument to models.ActionTypeFromString

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Valip
  • 4,440
  • 19
  • 79
  • 150
  • 2
    The error is self-explanatory: `type ActionType string` introduces a new type. You have to cast to `* string` – Imaxd May 22 '20 at 10:28
  • @mkopriva that worked, I tried some conversions before posting the question, but not like this. Thank you, maybe add your comment as an answer – Valip May 22 '20 at 10:30
  • 4
    Check this out for a deeper understanding: https://stackoverflow.com/q/19334542/2117591 – Imaxd May 22 '20 at 10:40

1 Answers1

0

The types *string and *actions.ActionType are not the same, string and actions.ActionType are also not the same. However they share the same underlying type which means you can convert one to the other. e.g. (*string)(newAction.ActionType).

As mentioned by @Imaxd in the comments, you can take a look at this answer for more details.

mkopriva
  • 35,176
  • 4
  • 57
  • 71
  • 2
    you could mention this question which is related https://stackoverflow.com/q/19334542/2117591 – Imaxd May 22 '20 at 10:37