如果Golang没有固有的,我该如何尝试构建它

Wan*_* Li -2 inheritance go

Golang中的struct没有构造函数,我们一般可以使用工厂模式来解决这个问题。但是我怎样才能尝试在工厂模式中实现继承呢?例如,这是我的一些代码:

在student.go中

package model

//a struct
type student struct{
 Name string
 score float64
}

//Because the initial letter of the student structure is lowercase, it can only be used in mods
func NewStudent(n string, s float64) *student {
 return &student{
  Name : n,
  score : s,
 }
}

//If the first letter of the score field is lowercase, then, in other packages not directly method, we can provide a method
func (s *student) GetScore() float64{
 return s.score //ok
}

Run Code Online (Sandbox Code Playgroud)

在main.go中

package main

import (
 "fmt"
 "factory/model"
)

func main() {
 //Create the Student instance to be given
 // var stu = model.Student{
 //  Name :"tom",
 //  Score : 78.9,
 // }

 //If the student structure is lowercase, we can solve it by using the factory pattern
 var stu = model.NewStudent("tom~", 98.8)

 fmt.Println(*stu) //&{....}
 fmt.Println("name=", stu.Name, " score=", stu.GetScore())
}
Run Code Online (Sandbox Code Playgroud)

我如何尝试在代码中实现继承?

Vol*_*ker 5

我如何尝试在代码中实现继承?

你不能。无论你尝试什么:你都会失败。

您必须在没有继承的情况下对问题进行建模。

(继承合并了几件事:代码重用和行为。在 Go 中,代码重用是通过函数完成的,行为是通过接口完成的。)