Golang

golang interface用法

golang interface测试 很不爽这种一眼看过去看不出一个struct实现了哪个interface的奇怪设计。但路依然是要走的,真香。。 测试代码1 package main import "fmt" type Task interface{ execute() } type CrontabTask struct{ } func (task CrontabTask) execute() { fmt.Println("crontab task!") } type QueueTask struct{ } func (task QueueTask) execute() { fmt.Println("queue task!") } type LoopTask struct{ } func (task LoopTask) execute() { fmt.Println("loop task!") } type WrongTask struct{ } func (task WrongTask) execute1() { fmt.Println("loop task!") } func main(){ var task Task task = new (CrontabTask) task.execut...

gomod使用方法

全在这里了 https://zhuanlan.zhihu.com/p/60703832

golang实现类

介绍 类,熟悉java c++ php python等语言中任意一门的人都不会陌生。我假设不行看到这篇文章的人,和我一样有其他高级语言经验。所以这里不废话什么是class。 golang实现 golang并没有提供class关键字来定义类。但是他有struct,并且我们可以给struct添加方法。这样子我们也可以达到实现类功能的目的。 我们来实现一个带有加(add)减(minus)乘(multiple)除(divide)四种操作的Calculator类吧。 首先我们定义一个Calculator接口 package main import "fmt" // 定义计算器的操作 type Calculator interface { add(x int, y int) int minus(x int, y int) int multiply(x int, y int) int divide(x int, y int) float32 } // 定义TestCalculator"类" type TestCalculator struct{ } func (consoleCalculator TestCalculator) add(x int, y int) int { return x + y } func (consoleCalcul...

Golang实现接口编程

介绍 接口是面向对象编程一种重要技术手段。一个接口中包含一组标准操作的签名,任意class只要实现了这个接口的方法,就可以被当做这个接口的子类型来调用。因为这个特性,我们就可以实现功能组件的即插即用,随意替换。 举个cache的例子,这里用java来写: public class Main { public static void main(String[] args){ Cache cache; // 输出:Redis缓存内容 cache = new RedisCache(); System.out.println(cache.get("key")); // 输出:File缓存内容 cache = new FileCache(); System.out.println(cache.get("key")); } } // 缓存接口 interface Cache { Object get(String key); void set(String key, Object value); void delete(String key); } // 基于redis的缓存 class RedisCache implem...

golang之内存管理make

介绍 读《network programming with golang》这本书,墙裂推荐。读这本书之前我并没有系统的学过这门语言。读到第十章,Dictionary内存分配的代码让我觉得有些困惑,为什么一个定义长度为100的数组不会越界 问题 书中代码如下 v := make([]*Entry, 0, 100) for n := 0; n < len(d.Entries); n++ { de := d.Entries[n] if de.Pinyin == py { v = append(v, de) } } 这段代码,看起来就是在最初创建了一个长度为100的数组,而后不断的通过append给它添加新的元素。添加多少个元素是不确定的,那么如果添加101个元素,会不会index of range呢? 实验 带着这个问题我做了如下实验。实验代码如下 package main import "fmt" func main(){ array := make([]int, 0, 10) // 越界错误: index out of range //array[0] = 1 // ok 可以访问 array = array[0:1] array[0] = 1 // 越界错误: in...
执行时间: 1710837107364.8 毫秒