I have my custom type alias (with methods) defined as:
type AwsRegion string
Then I want to pass variable of this type to another legacy (not under my control) function, that accepts pointer to string (pointer to underlying type):
func main() {
var region AwsRegion = "us-west-2"
f(®ion) // How to properly cast AwsRegion type here?
}
func f(s *string) {
fmt.Println(*s) // just an example
}
And of course I can't do that, error message states:
cannot use ®ion (type *AwsRegion) as type *string in argument to f
How to properly cast region
variable?
I do not understand why you need to define an AwsRegion
type if your input takes a string
as an input.
Use f(s *AwsRegion)
EDIT - as per your comments
package main
import (
"flag"
"fmt"
)
type AwsRegion string
var region AwsRegion
func main() {
flag.StringVar((*string)(®ion), "region", "us-west-1", "AWS region to use")
flag.Parse()
}
func f(s *string) {
fmt.Println(*s) // just an example
}
The region
variable should be casted to the pointer to string
type. But due to *
operator precedence, this should be done this way:
package main
import (
"fmt"
)
type AwsRegion string
func main() {
var region AwsRegion = "us-west-2"
f((*string)(®ion)) // parentheses required!
}
func f(s *string) {
fmt.Println(*s)
}
Link to playground