How do change all field "struct" without one? (using memory address)

Hi there

I want the “country” field does not change, that’s inside a map :

type Company struct{ CompanyName, Role, country string }

func changeName(A *map[string]Company) {
*A = map[string]Company{“dr”: {CompanyName: “CompanyBBB”, Role: “manager”, country: “U”},
“hamed”: {CompanyName: “CompanyBBB”, Role: “manager”, country: “U”},}
}

func main() {
var A = map[string]Company{“dr”: {CompanyName: “avaze”, Role: “manager”, country: “I”},
“hamed”: {CompanyName: “avaze”, Role: “softwarEngineer”, country: “I”},}
changeName(&A)
fmt.Println(“main (15):::”, A)
}

In other words, I want eliminated country in “change Name Func”
Any solution?

Here is Go playground :

Thanks in Advance.

Do you want to delete map element or what?

no, I want to don’t let to change “country” of “Company” struct after initialization.

https://play.golang.org/p/y8SVdrv1yZr

You need a map of pointers to Company because of this: https://github.com/golang/go/issues/3117

1 Like

Thanks, acim, Actually I compare this with JAVA which JAVA doesn’t let changes filed but I think Golang has not this capability.

public class User{
	private String company;
	private String role;
	private String country;

    public User(String company, String role, String country) {
		this.company = company;
		this.role = role;
		this.country = country;
	}

	public void setCompany(String company) {
		this.company = compnay;
	}

	public void setRole(String role) {
		this.role = role;
	}
}

The User Class doesn’t let to change(set) company after initialization.

Stop comparing Go and Java :smile:

You can have similar behaviour in Go using unexported fields in a struct.

1 Like

You have to encapsulate this in another package. For example your main.go may look like:

package main

import (

"fmt"

"path_to_to/types"

)

func main() {

user := types.NewUser("Jack", "Amazon", "guard")

user.SetCompany("Google")

fmt.Printf("%#v\n", user)

}

And then your types package (in types folder) would contain something like:

package types

type User struct {
	company string
	role    string
	country string
}

func NewUser(company, role, country string) *User {
	return &User{
		company: company,
		role:    role,
		country: country,
	}
}

func (u *User) SetCompany(company string) {
	u.company = company
}

func (u *User) SetRole(role string) {
	u.role = role
}
1 Like

Thanks, acim , I’ve forgotten this, That’s the solution.
Also, I am Golang side :slight_smile: