方法与接口(method Interface)
package interFaces
import (
"fmt"
"log"
)
// manager Appstore online account
type Account struct {
surName string
givenName string
}
// 方法的调用 如果需要对调用对象做修改操作,则需要使用 `*` 引用其指针创建方法。
func (a *Account) ChangeName() {
fmt.Printf("old surname:%s, givenName:%s\n", a.surName, a.givenName)
log.SetPrefix("ChangeName(): ")
var (
surName string
givenName string
)
fmt.Printf("Input New surName:\t ")
_, err := fmt.Scanf("%s\n", &surName)
// 值得注意的是,在使用Scanf进行键盘接收时,需要接收掉末尾的\n
if err != nil {
log.Fatalf("surName error:%v", err)
}
fmt.Printf("input new givenName:\t")
_, err = fmt.Scanf("%s", &givenName)
if err != nil {
log.Fatalf("givenName error:%v", err)
}
a.surName = surName
a.givenName = givenName
}
结构/方法的声明
type Employee struct {
loanLimit float32
Account
// 声明时: Account: Account{columnName: value1, columnName2: value2}
}
func (e *Employee) AddCredits(v float32) {
e.loanLimit += v
}
func (e *Employee) RemoveCredits(v float32) {
e.loanLimit -= v
if e.loanLimit < 0 {
e.loanLimit = 0
}
}
func (e Employee) CheckCredits() {
fmt.Println(e)
}
// 重写fmt.Println()调用的String()方法,其实标准打印Employee对象。
func (e Employee) String() string {
return fmt.Sprintf("Name: %s %s Credits:%5.2f", e.surName, e.givenName, e.loanLimit)
}
// 声明一个EmployeeTools的接口,服务于Employee类型对象
type EmployeeTools interface {
ChangeName()
AddCredits(v float32)
RemoveCredits(v float32)
CheckCredits()
}
func createEmployee(surname, givenName string) Employee {
var e2 *Employee = new(Employee)
// new()方法生成一个指定数据类型的对象,返回其指针
e2.surName, e2.givenName = surname, givenName
return *e2
}
接口的使用
func EmployeeMethod() {
var Students []Employee
var namelist map[string]string = map[string]string{
"Tom": "meh",
"Jeck": "marh",
"John": "Mark",
}
// 使用for循环结合 createEmployee()函数批量生成
for firstName, LastName := range namelist {
Students = append(Students, createEmployee(firstName, LastName))
}
Students[0].ChangeName()
Students[0].AddCredits(12.2)
//Students[0].CheckCredits()
for _, info := range Students {
fmt.Println(info)
}
}
标签:surName,string,示例,Students,Interfaces,Golang,Employee,givenName,fmt From: https://www.cnblogs.com/onlyEcho123/p/17731203.html