1.写出下面代码输出内容:

package main

import (
        "fmt"
)

func main() {
        defer_call()
}

func defer_call() {
        defer func() { fmt.Println("打印前") }()
        defer func() { fmt.Println("打印中") }()
        defer func() { fmt.Println("打印后") }()

        panic("触发异常")
}

输出结果:

打印后
打印中
打印前
panic: 触发异常

问题原因:

  • defer的执行顺序是逆序的,也就是先进后出的顺序;
  • panic在函数最终执行完毕才抛出异常;

2.这段代码能编译通过吗?

package main

import (
        "fmt"
)

type People interface {
        Speak(string) string
}

type Stduent struct{}

func (stu *Stduent) Speak(think string) (talk string) {
        if think == "bitch" {
                talk = "You are a good boy"
        } else {
                talk = "hi"
        }
        return
}

func main() {
        var peo People = Stduent{}
        think := "bitch"
        fmt.Println(peo.Speak(think))
}

输出结果:

# command-line-arguments
.\defer.go:23: cannot use Stduent literal (type Stduent) as type People in assignment:
        Stduent does not implement People (Speak method has pointer receiver)

问题原因: 接口赋值使用值作为参数传递var peo People = Stduent{}或者var peo People = &Stduent{};如果使用指针作为参数传递,则只能使用var peo People = &Stduent{}

3、下面这段代码输出的值为:

func main(){
        jsonStr := []byte(`{"age":1}`)
        var value map[string]interface{}
        json.Unmarshal(jsonStr,&value)
        age := value["age"]
        fmt.Println(reflect.TypeOf(age))
}

输出结果:

float64

问题原因: To unmarshal JSON into an interface value, Unmarshal stores one of these in the interface value:

  • bool, for JSON booleans
  • float64, for JSON numbers
  • string, for JSON strings
  • []interface{}, for JSON arrays
  • map[string]interface{}, for JSON objects
  • nil for JSON null

Json数据类型中没有整数,所有的数字类型在json中都存储为float64类型。

results matching ""

    No results matching ""