gopl-zh.github.com/ch12/ch12.md

6 lines
969 B
Markdown
Raw Permalink Blame History

This file contains invisible Unicode characters!

This file contains invisible Unicode characters that may be processed differently from what appears below. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to reveal hidden characters.

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

# 第12章 反射
Go语言提供了一种机制能够在运行时更新变量和检查它们的值、调用它们的方法和它们支持的内在操作而不需要在编译时就知道这些变量的具体类型。这种机制被称为反射。反射也可以让我们将类型本身作为第一类的值类型处理。
在本章我们将探讨Go语言的反射特性看看它可以给语言增加哪些表达力以及在两个至关重要的API是如何使用反射机制的一个是fmt包提供的字符串格式化功能另一个是类似encoding/json和encoding/xml提供的针对特定协议的编解码功能。对于我们在4.6节中看到过的text/template和html/template包它们的实现也是依赖反射技术的。然后反射是一个复杂的内省技术不应该随意使用因此尽管上面这些包内部都是用反射技术实现的但是它们自己的API都没有公开反射相关的接口。