K
K
kpa6uu2017-07-12 00:43:49
go
kpa6uu, 2017-07-12 00:43:49

Why do assignment errors occur when creating a type in Golang?

Greetings.
When trying to build the application, the following errors occur:

# command-line-arguments
./main.go:10: implicit assignment of unexported field 'login' in user.User literal
./main.go:11: implicit assignment of unexported field 'password' in user.User literal

main.go
package main

import (
  "fmt"
  "packageTest/user"
)

func main() {
  var bob = user.User {
    "Bob",
    "superbob",
  }

  fmt.Println(bob.GetLogin())
}

user/user.go
package user

type User struct {
  login string
  password string
}

func (User *User) GetLogin() string {
  return User.login
}

How can I overcome this error? What am I doing wrong? Thank you.
The nsa package is not used in this case.
FVuCcldpC0o.jpg
- - - - - - - - - - - - - - - - - - - - - -
UPD
Okay, renaming the login , password structure variables to CamelCase (made public) - everything became ok, the error disappeared.
But what should I do if I need to set private variables in this figurative constructor, which will be accessed through the methods of the structure?
type User struct {
  Login string
  Password string
}

- - - - - - - - - - - - - - - - - - - - -
UPD
According to
www.golangpatterns.info/object-oriented/constructors
https://stackoverflow.com/questions/18125625/const. ..
everything is bad

Answer the question

In order to leave comments, you need to log in

1 answer(s)
4
4X_Pro, 2017-07-12
@kpa6uu

Instead of a constructor, Go uses the NewClass function, i.e. in this case NewUser. It must be defined in package user:

func NewUser(login,password) {
return &User { login, password }
}

And call from main like this:
var bob = user.NewUser("Bob","superbob");

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question