在学习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)
}发布于 2017-04-19 19:23:44
IndexController.ChangeText需要一个指针接收器,或者IndexController.Model需要一个指针。您正在对SetText值的副本调用SetText。
如果您期望事物是可变的,那么在整个过程中始终使用指向结构的指针会更容易,并且在真正需要时将显式struct值作为异常。
https://stackoverflow.com/questions/43504240
复制相似问题