Answer the question
In order to leave comments, you need to log in
How to control the initialization of a Go variable?
How to control the initialization of a Go variable?
For example, in Java, C++, Python languages there is a constructor, when creating an object, I can definitely require you to set values for class variables.
class User {
private String m_name;
User(String name){
m_name = name;
}
void print(){
System.out.println("User name is " + m_name);
}
}
class Main {
public static void main(String[] args) {
User user = new User(); //ошибка компиляции
User user = new User("Alex"); //будет работать
user.print(); // выведет "User name is Alex"
}
}
type User struct {
name string
}
func (user *User) print() {
println("User name is " + user.name)
}
func main() {
user := User{name:"Alex"}
user.print() // Выведет User name is Alex
//сделать так, чтобы код, который ниже не работал, а требовал ввести name
user := User{}
user.print() // Выведет User name is
}
if name == "" {что то делать}
Answer the question
In order to leave comments, you need to log in
Usually, such a type is taken out into a separate package, the type is made private and the public function New, which returns the prepared object.
//// users/users.go
package users
type user struct {
name string
}
func New(name string) *user {
u := user{
name: name,
}
if name == "" {
u.name = "Nobody"
}
return &u
}
///// main.go
package main
import "github.com/yourproject/users"
func main() {
user := users.New("")
...........
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question