Access index of struct item field in Golang

Is there any possibility to change character with some index in struct field if it is string?
I mean I can do such manipulations with string type:

    func main() {
        v := "Helv"
        v[3] = "p"
    }

How can I do same thing with struct fields? Below assignment doesn’t work.

    type ik struct {
        a int
        b string
    }

    func main() {
        f := ik{1, "Pasis"}
        fmt.Println(f.b)
        f.b[2] = "r"
    }

I can’t do this even this way (without errors but nothing changes):

   type ik struct {
	a int
	b string
}

func main() {
	f := ik{1, "Pasis"}
	fmt.Println(f.b)

	x := f.b
	strings.Replace(x, string(x[0]), "r", 1)
	fmt.Println(x)
}

unfortunately, I do not know which string to be replaced. I mean for ex I’m getting struct from DB, Matching it’s one field (string) with regex, if it has 5 letters and start with “A”, i need to replace 2nd and 3rd letters with “*”. Can you advise how to achieve this?

if someone needs, I did it like this

package main

import (
	"fmt"
)

type ik struct {
	a int
	b string
}

func main() {
	f := ik{1, "Pasis"}
	fmt.Println(f.b)

	a := []byte(f.b)
	a[2] = 'r'
	f.b = string(a)
	fmt.Println(f.b)
	
}

Hey @kocharli, congrats on the first post :slight_smile:! Yeah, that makes sense since strings in go are immutable types (read-only byte slices). So, in reality, your first block of code wouldn’t work https://play.golang.org/p/Y9B0Clz7qKY

I found this https://blog.golang.org/strings reading very helpful at explaining how strings work in go.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.