BLACKMAMBA
BLACKMAMBA

Reputation: 725

Converting []*string to []string in golang

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!")
}

Upvotes: 4

Views: 2740

Answers (2)

nipuna
nipuna

Reputation: 4125

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

Upvotes: 6

Volker
Volker

Reputation: 42458

how do i convert []*string to []string

You cannot. This kind of type conversion not possible in Go.

is there any way to convert it using any utilities [...]

Asking for 3rd party libraries/tools/packages is OT on SO.

[...] or do i have to iterate it using a for-loop and construct an array

This is the only clean, normal, "idiomatic" way of doing this.

Upvotes: 2

Related Questions