i'm new to go.
i have a function that accepts []string as input, but i the input i have to pass is an []*string, how do i convert []*string to []string.
is there any way to convert it using any utilities, or do i have to iterate it using a for-loop and construct an array?
Playground link https://play.golang.org/p/_s2g7-IfGAy
package main
import (
"fmt"
)
func main() {
//Declaring an array of []*string and assigning value to it
var a [1]*string
var strPointer = new(string)
*strPointer = "1"
a[0] = strPointer
fmt.Println(*a[0])
// accept(a) this wont work
//Converting to array []string
var b []string
for i := range a {
b = append(b, *a[i])
}
accept(b)// this works
fmt.Println(b)
}
func accept(param []string) {
fmt.Println("Works!")
}
Your accept(param []string) expect a slice of string.
var a [1]*string This declares Go array with a length of 1. So it's not a slice.
You can declare an empty slice of string pointers using this. var a []*string
And you have to iterate through the array and make a slice with the value of pointer elements and call the accept with that slice.
Example function to convert []*string to []string
func stringer(str []*string) []string{
var strs []string
for _, s := range str {
if s == nil {
strs = append(strs, "")
continue
}
strs = append(strs, *s)
}
return strs
}
run here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With