Search code examples
pointersgoslicedereference

Is it possible in Go to pass pointer of string and make it slice of string?


So basically I was wondering if it possible in GO, because I was playing with Dereference.

For example in Code shown below. Pointer is passed to function and I'm trying to return one letter of passed pointer string, in given example that is H, but however slice can only be used with strings. And I was wondering if it possible to do this using pointer Dereference.

Code Example:

func Test(test *string) {
    if len(*test) > 0 {
        *test = *test[:1]
    }
    strings.ToUpper(*test)
}

func main() {
  str := "hello"
    Test(&str)
  fmt.Print( str)
}

Solution

  • You need to place test in brackets, i.e. dereference the pointer first, and then slice it.

    Then the Test function still wouldn't return capital H though, because ToUpper takes and returns a value. So you need to reassign the output of ToUpper to *test as well:

    func Test(test *string) {
        if len(*test) > 0 {
            *test = (*test)[:1] // bracketed `test`
        }
        *test = strings.ToUpper(*test) // reassign to `test`
    }
    
    func main() {
      str := "hello"
        Test(&str)
      fmt.Print(str) // Prints 'H'
    }
    

    Go Play example