go 我这里的代码一个不理解的报错,麻烦会的看下谢谢

报错信息是:serviceservice.go:38:11: assignment mismatch: 2 variables but 1 values
代码如下

package service

import (
    protos "dev/course/protos"
    "golang.org/x/net/context"
    "dev/course/router"
    "reflect"
    "errors"
    "log"
    "encoding/json"
    "fmt"
    // "os"
)

type CourseService struct {

}

func NewCourseService() *CourseService {
    return &CourseService{}
}

func (this *CourseService) Get(ctx context.Context, req *protos.CourseRequest) (*protos.CourseResponse, error) {
    result, err := this.Call(req.GetRouter(), req.GetParameters())
    if err != nil {
        // fmt.Println(err)
        log.Fatal(err)
    }

    DataJsonBytes, err := json.Marshal(result[0].Interface())
    if err != nil {
        fmt.Println(err)
        log.Fatal(err)
    }

    values := make(map[string]string)
    values["data"] = string(DataJsonBytes)
    if _, ok := result[2]; ok { // 报错在这一行!!!
        OtherJsonBytes, err := json.Marshal(result[2].Interface())
        if err != nil {
            log.Fatal(err)
        }
        values["other"] = string(OtherJsonBytes)
    }
    
    return &protos.CourseResponse{
        Status: 200,
        Values: values,
    }, nil
}

func (this *CourseService) Call(name string, params ... interface{}) (result []reflect.Value, err error) {
    if _, ok := router.Routers[name]; !ok {
        err = errors.New(name + " does not exist.")
        return
    }
    
    f := reflect.ValueOf(router.Routers[name])
    if len(params) != f.Type().NumIn() {
        err = errors.New("The number of params is not adapted.")
        return
    }

    in := make([]reflect.Value, len(params))
    for k, param := range params {
        in[k] = reflect.ValueOf(param)
    }
    
    result = f.Call(in)
    if result[1].Interface() != nil {
        err = result[1].Interface().(error)
    }
    return
}
阅读 7.7k
1 个回答

_, ok := result[2]
result[2]就一个值, 不能同时赋给两个变量_ok

你的写法对 map 管用, 但不是 array, 虽然他们看上去一个样
见下面的例子

package main

import "log"

func foo(){
    //map 正常
     mymap := make(map[int]string)
     mymap[1]="test1"
     mymap[2]="test2"
     log.Println(mymap)
     if _, isset := mymap[2]; isset {
         log.Println("you have 2")
     }

     if _, isset := mymap[3]; isset{
         log.Println("you NOT have 3")
     }


     //array 同样的办法会出错, 应使用 len 来判断

    result := []string {"1","a"}
    /*
    if _, ok := result[2]; ok { // 报错在这一行!!!
        log.Println("if")
    }
    */
    if len(result)>2 {
        log.Println("You can access the third element of array")
    }else{
        log.Println("There is no third element exists")
    }
}

func main(){
    foo()
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题