0

I'm trying to figure out what this expression does:

(*levelValue)(&level)

I don't understand what is happening, it seems like it dereferencing levelValue first, but not sure why as the type of levelValue is int32

Some context below

import "flag"

type Level int32
type levelValue Level

// LevelFlag defines a Level flag with specified name, default value and
// usage string. The return value is the address of a Level value that stores
// the value of the flag.
func LevelFlag(name string, defaultLevel Level, usage string) *Level {
    level := defaultLevel
    flag.Var((*levelValue)(&level), name, usage)
    return &level
}

func (l *levelValue) Set(s string) error {
    return (*Level)(l).UnmarshalText([]byte(s))
}

func (l *levelValue) String() string {
    return (*Level)(l).String()
}

Reference

1
  • 2
    FYI: Go is a statically typed language and does not support casting. What you are seeing above is a type conversion - which is allowed here since the one type derives from the other. Commented May 25, 2021 at 14:34

1 Answer 1

2

This is a type conversion:

When you define a type like that

type A B

You can convert a variable of type B to type A like that:

b := B
a := A(b)

In your case, the type A is (*levelValue) (The parenthesis are needed to specify that the type is a pointer to a levelValue. And the variable b is &level (A pointer that points to the variable level)

Sign up to request clarification or add additional context in comments.

3 Comments

thanks for the comment. "And the variable b is &level (A pointer that points to the variable level)" wouldn't b be the address of the variable level?
Yes one can say that it is the address of the variable
thanks, i think i was missing the idea of type conversion

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.