go语言学习笔记——函数

439 阅读1分钟

函数是go语言的一等公民,go语言是面向函数编程

go语言入参,除了能够像其他语言一样进行入参以外,还可以将函数作为入参进行执行。

package main

import (
	"fmt"
	"math/rand"
	"time"
)

func main() {
	funcRunTime := timeSpend(slow)
	fmt.Println(funcRunTime(10))
}

func timeSpend(inner func(op int) int) func(op int) int {
	return func(n int) int {
		start := time.Now()
		ret := inner(n)
		fmt.Println("time spent:", time.Since(start).Seconds())
		return ret
	}
}

func slow(op int) int {
	time.Sleep(time.Second + 1)
	return op
}

我解释下timeSpend的具体含义:

  1. 函数timeSpend的主要作用是计算“函数”的执行时间(这里我特意加了冒号)
  2. 函数timeSpend的传参是一个具体的“函数”,这个“函数”的入参和出参都是int
  3. inner表示,代码执行了这个“函数”的具体逻辑
  4. 输出执行时间

在我们一般的思维中,计算一个函数的执行时间,往往是在函数执行前、函数执行后分别打印一个时间戳,然后计算时间戳的差值,进行统计具体的执行时间。

以上代码,类似PHP代码


run();

function timeSpend($method, int $n)
{
    $start = time();
    $ret = $method($n);
    $executeTime = time() - $start;
    echo "time spent:" . $executeTime . "\n";
    return $ret;
}

function slow(int $n): int
{
    sleep(1);
    return $n;
}

function run()
{
    echo timeSpend("slow", 10);
}