关于后端:回答两个被频繁问到的代码写法问题

6次阅读

共计 1445 个字符,预计需要花费 4 分钟才能阅读完成。

前言

依据使用者的反馈,答复对于开源我的项目:go-gin-api 中被频繁问到的两个代码写法问题。

以如下代码片段为例:

  1. 第 8 行,这种写法是什么意思?
  2. 第 11 行,为什么定义一个 i() 办法?

问题一

var _ Signature = (*signature)(nil)

这代码是什么意思?

强制 *signature 去实现 Signature 接口,编译器会查看 *signature 类型是否实现了 Signature 接口。

来看一个例子:

package main

import "fmt"

var _ Study = (*study)(nil)

type study struct {Name string}

type Study interface {Listen(message string) string
}

func main() {fmt.Println("hello world")
}

下面代码会输入 hello world 吗?

不会!

这时会输入:

./main.go:5:5: cannot use (*study)(nil) (type *study) as type Study in assignment:
    *study does not implement Study (missing Listen method)

如果去掉这一行:

var _ Study = (*study)(nil)

这时就能够输入 hello world 了。

问题二

i()

为什么在接口中定义一个 i() 办法?

强制 Signature 接口中所有办法只能在本包中去实现,在其余包中不容许去实现。因为接口中有小写办法,所以在其余包无奈去实现。i() 示意一个小写办法,起其余名字也能够。

来看一个例子:

package study

type Study interface {Listen(message string) string
    i()}

func Speak(s Study) string {return s.Listen("abc")
}

定义了一个 Study 接口,接口中蕴含两个办法,其中就有一个 i()。

定义了一个 Speak 办法,入参是 Study 接口,办法体是执行接口中的 Listen 办法。

接下来看另一个文件:

type stu struct {Name string}

func (s *stu) Listen(message string) string {return s.Name + "听" + message}

func (s *stu) i() {}

func main() {message := study.Speak(new(stu))
    fmt.Println(message)
}

定义了一个 stu 构造体,这个构造体实现了 Study 接口中的办法,那么上述程序会失常输入吗?

不会!

这时会输入:

./main.go:19:28: cannot use new(stu) (type *stu) as type study.Study in argument to study.Speak:
    *stu does not implement study.Study (missing study.i method)
        have i()
        want study.i()

如果去掉接口中 i(),会失常输入:听 abc

小结

以上两个是读者在学习代码的过程中最常问的问题,心愿这次可能帮大家解惑。

另外 option 设计模式 ,问的也不少,大家能够看下这篇文章:《函数的不定参数你是这样用吗?》

举荐浏览

  • 对于分布式事务的了解
  • 依据使用者反馈,对开源我的项目 go-gin-api 新增两个性能
  • 对于解决电商零碎订单状态的流转,分享下我的技术计划(附带源码)
  • 我是怎么写 Git Commit message 的?
正文完
 0