13. 方法

package main

import (
    "fmt"
)

type User struct {
    username string
    password string
    age int
}

func (user *User) user_init(username, password string, age int) {
    user.username = username;
    user.password = password;
    user.age = age;
}

func (user *User) user_dump() {
    fmt.Printf("username = %s
", user.username)
    fmt.Printf("password = %s
", user.password)
    fmt.Printf("age = %d
", user.age)
}

func main() {
    var user User
    user.user_init("root", "123456", 25)
    user.user_dump()
}

在结构体基础上增加了方法,似乎实现了面向对象,但是Go语言并不是面向对象语言,只是增加了类似面向对象的语法。

原文地址:https://www.cnblogs.com/hatsusakana/p/9829749.html