Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

391
Views
How to use switch case with nullable string (*string) in Golang?

Here is my code:

func ToSomething(arg *string) string {
    switch arg {
    case nil:
        return "something1"
    case "args1":
        return "something2"
    case "args2":
        return "something3"
    default:
        return "something4"
    }
}

It shows a red line under args1 and args2 that says

Invalid case '"args1"' in switch on 'arg' (mismatched types 'string' and '*string')

anyone knows to use switch case with nullable string (*string) properly in golang?

Here is a go playground: https://go.dev/play/p/0TaeXSEIt06

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Each case must be the same type as arg. In your example, arg is *string and each case is string.

You could dereference arg:

func ToSomething(arg *string) string {
    if arg == nil {
        return "something1"
    }
    switch *arg {
    case "args1":
        return "something2"
    case "args2":
        return "something3"
    default:
        return "something4"
    }
}

Here is the playground.

over 4 years ago · Santiago Trujillo Report

0

Since arg is of type *string, you'd have to list values of *string in the case branches.

But! You obviously want to match the pointed string values, so listing *string values is not what you want: that checks for pointer equality.

So instead you should not use arg as the switch expression, but provide sensible conditions on the case branches like this:

func ToSomething(arg *string) string {
    switch {
    case arg == nil:
        return "something1"
    case *arg == "args1":
        return "something2"
    case *arg == "args2":
        return "something3"
    default:
        return "something4"
    }
}

Testing it:

ptr := func(s string) *string { return &s }

fmt.Println(ToSomething(nil))
fmt.Println(ToSomething(ptr("args1")))
fmt.Println(ToSomething(ptr("args2")))
fmt.Println(ToSomething(ptr("xx")))

Output (try it on the Go Playground):

something1
something2
something3
something4
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!