Rohman HM
Rohman HM

Reputation: 2837

Go - Cannot use as type in assignment

I'm new in Go Lang.

I confused why this error message still coming.

cannot use cmd.Args() (type cli.Args) as type CmdArgs in assignment

The error message explain that cmd.Args() (type cli.Args) cannot assignment to type CmdArgs which is type CmdArgs is cli.Args.

I have read Cannot use as type in assignment in go, but it does not make me understand where's my wrong is. I think that's a different matter with me.

Any solution please?

Here's my code.

package main

import (
    "fmt"
    "os"

    "github.com/urfave/cli"
)

// CmdArgs is command arguments
type CmdArgs cli.Args

func main() {
    program := cli.NewApp()
    program.Action = func(cmd *cli.Context) error {
        var args CmdArgs
        args = cmd.Args()
               ▼▼▼▼▼▼▼▼▼
               cannot use cmd.Args() (type cli.Args) as type CmdArgs in assignment

        return nil
    }

    program.Run(os.Args)
}

Thanks for your attention.

Upvotes: 1

Views: 7717

Answers (2)

Lukas Isselbächer
Lukas Isselbächer

Reputation: 911

args is a variable of type CmdArgs which has a vairable of type cli.Args

Change your function to

package main

import (
    "fmt"
    "os"

    "github.com/urfave/cli"
)

func main() {
    program := cli.NewApp()
    program.Action = func(cmd *cli.Context) error {
        args := cmd.Args()
        return nil
    }

    program.Run(os.Args)
}

and it should run.

Upvotes: 1

Adrian
Adrian

Reputation: 46602

The error means exactly what it says: you're trying to assign the return value of a function to a variable that's of a different type than the return value, which is invalid. When you define a new type, it's a new type, and not directly assignable. You can cast between them, but there is no implicit casting in Go - the cast must be done explicitly:

    var args CmdArgs
    normalArgs := cmd.Args()
    args = CmdArgs(normalArgs)

Though I have to wonder why you're creating a new type CmdArgs to begin with, but I assume there's some reason that's not indicated in the code example. You might have an easier time embedding rather than aliasing, however.

Upvotes: 1

Related Questions