当前位置: 首页 > news >正文

Go语言现代web开发15 泛型和错误

泛型

Generics are new concepts added in Go version 1.18. Designers have long fought against adding support for generic, citing that it would break the simplicity of the design, and the empty interface can be used instead of it.

泛型是Go 1.18版本中添加的新概念。设计师们长期以来一直反对增加对通用的支持,理由是它会破坏设计的简单性,而且可以用空接口来代替它。

When can we use generics? If we want to have a function that checks if an element is present in the array, we must declare a function for each type (integer arrays, string arrays, and so on). Generally, these functions will have the same code base, iterate through the array, and check if the current element is the one we are looking for.

什么时候可以使用泛型?如果希望有一个检查数组中是否存在元素的函数,则必须为每种类型(整数数组、字符串数组等)声明一个函数。通常,这些函数将具有相同的代码库,遍历数组,并检查当前元素是否为我们要查找的元素。

We can create a generic function by introduding the type parameter (in square brackets between the function name and function arguments), and use it in the function signature. Here is an example of Contains() function implemented with generics.

我们可以通过引入类型参数(在函数名和函数实参之间的方括号中)来创建泛型函数,并在函数签名中使用它。下面是一个用泛型实现的Contains()函数的例子。

func Contains[T comparable](s []T, e T) bool {for _, a := range s {if a == e {return true}}return false
}func main() {arr := []int{1, 2, 3, 4, 5}arr2 := []string{"a", "b", "c", "d"}fmt.Println(Contains(arr, 3))fmt.Println(Contains(arr2, "c"))
}

T can be any type that fulfills compareable constraints (all types that support equality operators == and !=).

T 可以是任意的,支持 == 和 != 比较运算符的类型。

Besides function generics, we can declare generic types. In the next example, we will define a type for the node which can be used in the implementation of a binary tree. In binary trees, each node can reference at most two other nodes(usually called left and right child) and hold value.

除了函数泛型,我们还可以声明泛型类型。在下一个示例中,我们将为节点定义一个类型,该类型可用于二叉树的实现。在二叉树中,每个节点最多可以引用两个其他节点(通常称为左子节点和右子节点)并保持值。

type Node[T any] struct {leftChild  *Node[T]rightChild *Node[T]value      T
}

Constraint any is basically an alias for the empty interface, so any type can be used in place of T.

约束any基本上是空接口的别名,因此任何类型都可以用来代替T。

panic 错误处理

Panic is a built-in function that stops the regular flow, similar to the concept of runtime exceptions from other programming language (Java). When it is triggered, the message printed on standard output and function execution will be terminated.

Panic是一个停止常规流的内置函数,类似于其他编程语言(Java)中的运行时异常概念。当它被触发时,在标准输出和函数执行上打印的消息将被终止。

Panic is often triggered by unexpected errors. Some examples of the most common unexpected errors are:

  • Invalid memoery address or nil pointer difference
  • Divide by zero
  • Index out of range

恐慌通常是由意想不到的错误引发的。一些最常见的意外错误的例子是:

  • 无效的内存地址或空指针差异
  • 除以零
  • 索引超出范围

In the following example, panic Index out of range will be triggered.

在下面的示例中,索引越界的异常将会被触发。

func main() {s:= []int{1,2,3}fmt.Println(s[3])
}

Panic can be explicitly triggered in code by calling pani() function. This is often used for error handling, like in the following example.

可以通过调用pani()函数在代码中显式触发Panic。这通常用于错误处理,如下面的示例所示。

func checkName(name string) {if name == "" {panic("Invalid name!!!")}
}

It is not a good practice to use panics for normal error handling.

将panic用于正常的错误处理并不是一个好的做法。

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • 探索Python中的装饰器
  • C++ char*和char[] 可能指向的内存区域详解(附实验)
  • 安卓BLE蓝牙通讯
  • Ubuntu搭建FTP服务器
  • K8s1.28 部署Dashboard获取登录信息
  • 【最新华为OD机试E卷-支持在线评测】最长连续子序列(100分)多语言题解-(Python/C/JavaScript/Java/Cpp)
  • 基于鸿蒙API10的RTSP播放器(七:亮度调节功能测试)
  • 基于微信小程序的宠物之家的设计与实现
  • 1. TypeScript基本语法
  • ‌移动管家手机智能控制汽车系统
  • 力扣刷题(6)
  • 唯徳知识产权管理系统 DownloadFileWordTemplate 文件读取漏洞复现
  • 【Linux】Ubuntu 22.04 shell实现MySQL5.7 tar 一键安装
  • LeetCode[中等] 合并区间
  • C++ | Leetcode C++题解之第400题第N位数字
  • [译]如何构建服务器端web组件,为何要构建?
  • 【跃迁之路】【463天】刻意练习系列222(2018.05.14)
  • node-sass 安装卡在 node scripts/install.js 解决办法
  • PHP那些事儿
  • Python - 闭包Closure
  • SOFAMosn配置模型
  • Swoft 源码剖析 - 代码自动更新机制
  • TiDB 源码阅读系列文章(十)Chunk 和执行框架简介
  • Webpack入门之遇到的那些坑,系列示例Demo
  • 测试开发系类之接口自动化测试
  • 记一次和乔布斯合作最难忘的经历
  • 将回调地狱按在地上摩擦的Promise
  • 坑!为什么View.startAnimation不起作用?
  • 学习JavaScript数据结构与算法 — 树
  • ​软考-高级-系统架构设计师教程(清华第2版)【第9章 软件可靠性基础知识(P320~344)-思维导图】​
  • (1)(1.9) MSP (version 4.2)
  • (1)STL算法之遍历容器
  • (23)Linux的软硬连接
  • (24)(24.1) FPV和仿真的机载OSD(三)
  • (27)4.8 习题课
  • (C语言)fgets与fputs函数详解
  • (Spark3.2.0)Spark SQL 初探: 使用大数据分析2000万KF数据
  • (二)c52学习之旅-简单了解单片机
  • (六)激光线扫描-三维重建
  • (七)c52学习之旅-中断
  • (译)计算距离、方位和更多经纬度之间的点
  • (杂交版)植物大战僵尸
  • (转)Google的Objective-C编码规范
  • (转)memcache、redis缓存
  • ***汇编语言 实验16 编写包含多个功能子程序的中断例程
  • .NET 8.0 中有哪些新的变化?
  • .NET 中小心嵌套等待的 Task,它可能会耗尽你线程池的现有资源,出现类似死锁的情况
  • .NET中使用Protobuffer 实现序列化和反序列化
  • .Net转前端开发-启航篇,如何定制博客园主题
  • /run/containerd/containerd.sock connect: connection refused
  • @Builder用法
  • [ C++ ] STL---string类的模拟实现
  • [2669]2-2 Time类的定义
  • [AI aider] 打造终端AI搭档:Aider让编程更智能更有趣!
  • [Bada开发]初步入口函数介绍