1

Some code I am using flags for managing the program or service. Today I got the problem, where I wanted to use this kind of declaration:

var port = flag.String("port", "", "port")

It is return back a *string type variable what I can't convert to string. How I managed the problem:

r.Run(":" + *port)

It is working but what is the best practice for that? I mean there are loads of function which is waiting string as parameter, and in this case I can't handle that.

2
  • Anything returned by the flag package functions is a pointer, since it needs to be modified "behind the scenes". You're probably better off using a flag.Int, though, since you're currently open for someone to call your program with "-flag crashy", which will most likely cause a panic. Commented Oct 20, 2016 at 10:56
  • 1
    Well, then use flag.StringVar. Sometimes reading the package documentation really does help. Commented Oct 20, 2016 at 11:18

2 Answers 2

10

Your port variable is of type *string (this is what flag.String() returns). To get a value of type string, there's no other way than to dereference it: *port.

You may do so at every place where you need to pass it as a string, or you may use flag.StringVar() instead:

var port string

func init() {
    flag.StringVar(&port, "port", "", "port")
}

In this case, your port variable is of type string, so no dereferencing is needed. Here you explicitly provide a *string value to the flag package to be used: the address of your variable of type string, which will be of type *string of course (so the flag package will be able to modify / set the pointed value). The flag.String() is a convenience function which allocates a string value and returns you the pointer to it.

Another option would be to dereference it once and store the string value in another variable of type string, for example:

var portp = flag.String("port", "", "port")
var port string

func main() {
    flag.Parse()
    port = *portp
    // Now you can use port which is of type string
}

But I prefer the flag.StringVar() solution.

Note that however a port is a number, you may be better off using flag.Int() or flag.IntVar():

var port int

func init() {
    flag.IntVar(&port, "port", 0, "port")
}
Sign up to request clarification or add additional context in comments.

Comments

0

You should be able to use it as is or just convert it to a string.

package main

import "fmt"
import "flag"

func main () {

    var port = flag.String("port", "", "port")
    flag.Parse()

    test(*port)

    newstring := *port

    test(newstring)
}

func test (s string) {

    fmt.Println(s)

}

Comments

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.