我正在尝试在学习Go时尝试理解MVC架构,并且我试图从控制器中更改模型中的值。
现在代码创建一个只保存字符串的模型,视图显示终端上的字符串,但控制器无法更改它(它可以毫无问题地获得用户输入)。
现在我在终端上的文字是这样的:
Hello World!
asdf //my input
Hello World!
我希望得到的输出是这样的:
Hello World!
asdf //my input
asdf
以下是我的文件:
model.go
package models
type IndexModel struct {
Text string
}
func (m *IndexModel) InitModel() string {
return m.Text
}
func (m *IndexModel) SetText(newText string) {
m.Text = newText
}
view.go
package views
import "github.com/jufracaqui/mvc_template/app/models"
type IndexView struct {
Model models.IndexModel
}
func (v IndexView) Output() string {
return v.Model.Text
}
controller.go
package controllers
import "github.com/jufracaqui/mvc_template/app/models"
type IndexController struct {
Model models.IndexModel
}
func (c IndexController) ChangeText(userInput string) {
c.Model.SetText(userInput)
}
main.go:
package main
import (
"bufio"
"os"
"fmt"
"github.com/jufracaqui/mvc_template/app/controllers"
"github.com/jufracaqui/mvc_template/app/models"
"github.com/jufracaqui/mvc_template/app/views"
)
func main() {
handleIndex()
}
func handleIndex() {
model := models.IndexModel{
"Hello World!",
}
controller := controllers.IndexController{
model,
}
viewIndex := views.IndexView{
model,
}
fmt.Println(viewIndex.Model.Text)
reader := bufio.NewReader(os.Stdin)
text, _ := reader.ReadString('\n')
controller.ChangeText(text)
fmt.Println(viewIndex.Model.Text)
}
修改 在@JimB回答之后我的代码如何结束:
model.go:
package models
type IndexModel struct {
Text string
}
func (m *IndexModel) InitModel() string {
return m.Text
}
view.go:
package views
import "github.com/jufracaqui/mvc_template/app/models"
type IndexView struct {
Model *models.IndexModel
}
func (v IndexView) Output() string {
return v.Model.Text
}
controller.go:
package controllers
import "github.com/jufracaqui/mvc_template/app/models"
type IndexController struct {
Model *models.IndexModel
}
func (c IndexController) ChangeText(userInput string) {
c.Model.Text = userImput
}
main.go:
package main
import (
"bufio"
"os"
"fmt"
"github.com/jufracaqui/mvc_template/app/controllers"
"github.com/jufracaqui/mvc_template/app/models"
"github.com/jufracaqui/mvc_template/app/views"
)
func main() {
handleIndex()
}
func handleIndex() {
model := models.IndexModel{
"Hello World!",
}
m := &model
controller := controllers.IndexController{
m,
}
viewIndex := views.IndexView{
m,
}
fmt.Println(viewIndex.Model.Text)
reader := bufio.NewReader(os.Stdin)
text, _ := reader.ReadString('\n')
controller.ChangeText(text)
fmt.Println(viewIndex.Model.Text)
}
答案 0 :(得分:7)
IndexController.ChangeText
需要一个指针接收器,或IndexController.Model
需要一个指针。您在SetText
值的副本上调用了SetText
。
如果您希望事物是可变的,那么始终使用指向结构的指针要容易得多,并且在您真正需要它时使显式结构值成为异常。