U
U
ubsa2019-10-12 15:24:07
Java
ubsa, 2019-10-12 15:24:07

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

How can I implement the same behavior in go?
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 
}

Or does Go not know how and you need to check it yourself in the method?:
if name == "" {что то делать}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Pavlyuk, 2019-10-12
@pav5000

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 question

Ask a Question

731 491 924 answers to any question