缺少函数体

huangapple go评论69阅读模式
英文:

Missing function body

问题

当我在Golang中看到math.Sin时,我感到困惑,因为它是两个同名函数,但第一个函数没有函数体。

例如math.Acos

// Acos returns the arccosine, in radians, of x.
//
// Special case is:
//	Acos(x) = NaN if x < -1 or x > 1
func Acos(x float64) float64

func acos(x float64) float64 {
	return Pi/2 - Asin(x)
}

但是当我想用以下语句创建一个非常简单的uuid包时:

package uuid

import (
	"crypto/rand"
	"fmt"
	"io"
)

// Generate generates a random UUID according to RFC 4122
func Generate() (string, error)

func generate() (string, error) {
	uuid := make([]byte, 16)
	n, err := io.ReadFull(rand.Reader, uuid)
	if n != len(uuid) || err != nil {
		return "", err
	}
	uuid[8] = uuid[8]&^0xc0 | 0x80
	uuid[6] = uuid[6]&^0xf0 | 0x40
	return fmt.Sprintf("%x-%x-%x-%x-%x", uuid[0:4], uuid[4:6], uuid[6:8], uuid[8:10], uuid[10:]), nil
}

我得到了一个错误,说“Generate缺少函数体”。

那么我该如何编写像math.Acos这样的函数呢?

英文:

When I saw math.Sin in Golang , I wondered because it was two functions with same names but first function have not function body.
See below :

For example math.Acos :

// Acos returns the arccosine, in radians, of x.
//
// Special case is:
//	Acos(x) = NaN if x &lt; -1 or x &gt; 1
func Acos(x float64) float64

func acos(x float64) float64 {
	return Pi/2 - Asin(x)
}

But when I want to create a very very simple uuid package with below statements :

package uuid

import (
	&quot;crypto/rand&quot;
	&quot;fmt&quot;
	&quot;io&quot;
)

// Generate generates a random UUID according to RFC 4122
func Generate() (string, error)

func generate() (string, error) {
	uuid := make([]byte, 16)
	n, err := io.ReadFull(rand.Reader, uuid)
	if n != len(uuid) || err != nil {
		return &quot;&quot;, err
	}
	uuid[8] = uuid[8]&amp;^0xc0 | 0x80
	uuid[6] = uuid[6]&amp;^0xf0 | 0x40
	return fmt.Sprintf(&quot;%x-%x-%x-%x-%x&quot;, uuid[0:4], uuid[4:6], uuid[6:8], uuid[8:10], uuid[10:]), nil
}

I've got an error that said missing function body for &quot;Generate&quot;

So how can I write functions like math.Acos ?

答案1

得分: 3

acosAcos是不同的函数,具有不同的实现方式。同样,你的Generate()generate()也是如此。

acos方法是用汇编实现的,这只是方法的原型。你不需要预先声明UUID生成函数,因为编译器是多通道的。

英文:

acos and Acos are different functions, with differing implementations. The same with your Generate() and generate().

The acos method is implemented in assembly, and this is just the method prototype. You do not need to pre-declare your UUID generation function, as the compiler is multi-pass.

huangapple
  • 本文由 发表于 2017年5月17日 14:59:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/44017725.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定