/*第一题
package main
import "fmt"
type employee struct {
salary float64
}
func (e *employee)giveRaise(){
e.salary=e.salary*(1+0.1)
}
func main () {
var e1 employee
e1.salary=3000
e1.giveRaise()
fmt.Printf("增加后的工资是:%.2f",e1.salary)
}
*/
/*第二题
package main
import "fmt"
type Base struct {
id int
}
type Person struct {
Base
FirstName string
LastName string
}
type employee struct {
Person
salary float64
}
func (e *Base)Id() int{
return e.id
}
func (h *Base)setid(){
h.id=666
return
}
func main () {
var e1 employee
e1.id=123
e1.salary=10000
e1.FirstName="nihao"
fmt.Println("原id",e1)
e1.setid()
e1.FirstName="nihao"
fmt.Println("新id",e1)
}
*/
/*第三题
package main
import "fmt"
type Person struct {
id int
name string
age int
sex string
}
type student struct {
Person
class string
score float64
}
func main () {
var s1 student
s1.id=10001
s1.name="张三"
s1.age=20
s1.sex="男"
s1.class="区块链2201"
s1.score=75.6
fmt.Print(s1)
}
*/
/*第四题
package main
import "fmt"
type Inteliphone struct {
Brand string
Camera
Phone
Internet
}
type Camera struct {
action string
}
type Phone struct {
action string
}
type Internet struct {
action string
}
func (e *Camera)photograph(){
s.action="take a picture"
fmt.Printf("device.photograph()执行动作:%+v\n",s.action)
return
}
func (e *Phone)call(){
s.action="dial-up"
fmt.Printf("device.call()执行动作:%+v\n",s.action)
return
}
func (e *Internet)goweb(){
s.action="access network"
fmt.Printf("device.goweb()执行动作:%+v\n",s.action)
return
}
func main () {
device:=Inteliphone(Brand:"redmi k60 pro")
device.photograph()
device.call()
device.goweb()
fmt.Printf("smartphone动作汇总:+v\n",device)
}
*/
/*第四题代码存在以下错误:
1. 在定义Inteliphone结构体时,Camera、Phone和Internet应该是结构体的字段,而不是类型。
2. 在定义Camera、Phone和Internet结构体时,action字段应该是公开的,即首字母大写。
3. 在定义photograph、call和goweb方法时,方法接收者应该是Inteliphone结构体类型的指针,而不是Camera、Phone和Internet结构体类型的指针。
4. 在方法中,应该使用接收者的字段名来设置动作,而不是使用未定义的变量s。
5. 在main函数中,应该使用字面量语法创建Inteliphone结构体对象。
以下是修改后的代码:*/
package main
import "fmt"
type Inteliphone struct {
Brand string
Camera Camera
Phone Phone
Internet Internet
}
type Camera struct {
Action string
}
type Phone struct {
Action string
}
type Internet struct {
Action string
}
func (i *Inteliphone) Photograph() {
i.Camera.Action = "take a picture"
fmt.Printf("device.photograph()执行动作:%+v\n", i.Camera.Action)
}
func (i *Inteliphone) Call() {
i.Phone.Action = "dial-up"
fmt.Printf("device.call()执行动作:%+v\n", i.Phone.Action)
}
func (i *Inteliphone) GoWeb() {
i.Internet.Action = "access network"
fmt.Printf("device.goweb()执行动作:%+v\n", i.Internet.Action)
}
func main() {
device := Inteliphone{
Brand: "redmi k60 pro",
Camera: Camera{
Action: "",
},
Phone: Phone{
Action: "",
},
Internet: Internet{
Action: "",
},
}
device.Photograph()
device.Call()
device.GoWeb()
fmt.Printf("smartphone动作汇总:%+v\n", device)
}