main.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  1. package main
  2. import (
  3. "errors"
  4. "fmt"
  5. "strings"
  6. )
  7. func main() {
  8. fmt.Println("=== Go 接口、类型断言和类型转换演示 ===\n")
  9. // 1. 接口基本演示
  10. demoInterface()
  11. // 2. 空接口演示
  12. demoEmptyInterface()
  13. // 3. 类型断言演示
  14. demoTypeAssertion()
  15. // 4. 类型转换演示
  16. demoTypeConversion()
  17. // 5. 综合应用示例
  18. demoComprehensive()
  19. }
  20. // ================================
  21. // 1. 接口定义和实现
  22. // ================================
  23. // Writer 接口定义
  24. type Writer interface {
  25. Write([]byte) (int, error)
  26. }
  27. // Reader 接口定义
  28. type Reader interface {
  29. Read([]byte) (int, error)
  30. }
  31. // ReadWriter 组合接口
  32. type ReadWriter interface {
  33. Reader
  34. Writer
  35. }
  36. // File 结构体实现接口
  37. type File struct {
  38. name string
  39. }
  40. // File 实现 Writer 接口
  41. func (f File) Write(data []byte) (int, error) {
  42. fmt.Printf("Writing to %s: %s\n", f.name, string(data))
  43. return len(data), nil
  44. }
  45. // File 实现 Reader 接口
  46. func (f File) Read(data []byte) (int, error) {
  47. content := fmt.Sprintf("Content from %s", f.name)
  48. copy(data, []byte(content))
  49. fmt.Printf("Reading from %s\n", f.name)
  50. return len(content), nil
  51. }
  52. func demoInterface() {
  53. fmt.Println("1. 接口基本演示:")
  54. fmt.Println("----------------")
  55. var w Writer = File{"example.txt"}
  56. w.Write([]byte("Hello World"))
  57. var r Reader = File{"data.txt"}
  58. r.Read(make([]byte, 50))
  59. var rw ReadWriter = File{"readwrite.txt"}
  60. rw.Write([]byte("Data to write"))
  61. rw.Read(make([]byte, 50))
  62. fmt.Println()
  63. }
  64. // ================================
  65. // 2. 空接口演示
  66. // ================================
  67. // printAnything 接受任何类型的空接口参数
  68. func printAnything(v interface{}) {
  69. fmt.Printf("值: %v, 类型: %T\n", v, v)
  70. }
  71. func demoEmptyInterface() {
  72. fmt.Println("2. 空接口演示:")
  73. fmt.Println("----------------")
  74. printAnything(42) // int
  75. printAnything("hello") // string
  76. printAnything([]int{1, 2, 3}) // slice
  77. printAnything(3.14) // float64
  78. printAnything(true) // bool
  79. fmt.Println()
  80. }
  81. // ================================
  82. // 3. 类型断言演示
  83. // ================================
  84. // Animal 接口
  85. type Animal interface {
  86. Speak() string
  87. }
  88. // Dog 实现 Animal 接口
  89. type Dog struct{ name string }
  90. func (d Dog) Speak() string {
  91. return "Woof! My name is " + d.name
  92. }
  93. // Cat 实现 Animal 接口
  94. type Cat struct{ name string }
  95. func (c Cat) Speak() string {
  96. return "Meow! My name is " + c.name
  97. }
  98. // checkType 使用类型断言检查接口类型
  99. func checkType(i interface{}) {
  100. switch v := i.(type) {
  101. case int:
  102. fmt.Printf("整数: %d\n", v)
  103. case string:
  104. fmt.Printf("字符串: %s\n", v)
  105. case bool:
  106. fmt.Printf("布尔值: %t\n", v)
  107. case Dog:
  108. fmt.Printf("狗狗在说话: %s\n", v.Speak())
  109. case Cat:
  110. fmt.Printf("猫咪在说话: %s\n", v.Speak())
  111. default:
  112. fmt.Printf("未知类型: %T\n", v)
  113. }
  114. }
  115. func demoTypeAssertion() {
  116. fmt.Println("3. 类型断言演示:")
  117. fmt.Println("----------------")
  118. // 基本类型断言
  119. var i interface{} = "hello world"
  120. // 安全的方式:检查是否成功
  121. if s, ok := i.(string); ok {
  122. fmt.Printf("断言成功,是字符串: %s\n", s)
  123. } else {
  124. fmt.Println("不是字符串")
  125. }
  126. // 检查其他类型失败的情况
  127. if n, ok := i.(int); ok {
  128. fmt.Printf("是整数: %d\n", n)
  129. } else {
  130. fmt.Println("不是整数")
  131. }
  132. // 类型switch演示
  133. fmt.Println("\n类型switch演示:")
  134. checkType(42)
  135. checkType("golang")
  136. checkType(true)
  137. checkType(Dog{"Buddy"})
  138. checkType(Cat{"Kitty"})
  139. // 接口类型断言
  140. fmt.Println("\n接口类型断言:")
  141. var a Animal = Dog{"Rex"}
  142. if dog, ok := a.(Dog); ok {
  143. fmt.Println("这是一只狗:", dog.Speak())
  144. }
  145. a = Cat{"Mimi"}
  146. if cat, ok := a.(Cat); ok {
  147. fmt.Println("这是一只猫:", cat.Speak())
  148. }
  149. fmt.Println()
  150. }
  151. // ================================
  152. // 4. 类型转换演示
  153. // ================================
  154. // 自定义温度类型
  155. type Celsius float64
  156. type Fahrenheit float64
  157. // 温度转换函数
  158. func CToF(c Celsius) Fahrenheit {
  159. return Fahrenheit(c*9/5 + 32)
  160. }
  161. func FToC(f Fahrenheit) Celsius {
  162. return Celsius((f - 32) * 5 / 9)
  163. }
  164. // 为Celsius实现String方法
  165. func (c Celsius) String() string {
  166. return fmt.Sprintf("%.1f°C", c)
  167. }
  168. func (f Fahrenheit) String() string {
  169. return fmt.Sprintf("%.1f°F", f)
  170. }
  171. func demoTypeConversion() {
  172. fmt.Println("4. 类型转换演示:")
  173. fmt.Println("----------------")
  174. // 基本类型转换
  175. var integer int = 42
  176. var floatNum float64 = float64(integer)
  177. var unsigned uint = uint(floatNum)
  178. fmt.Printf("整数: %d, 浮点数: %.2f, 无符号整数: %d\n",
  179. integer, floatNum, unsigned)
  180. // 字符串和字节切片转换
  181. text := "Hello, Go!"
  182. bytes := []byte(text)
  183. textAgain := string(bytes)
  184. fmt.Printf("原字符串: %s\n", text)
  185. fmt.Printf("字节切片: %v\n", bytes)
  186. fmt.Printf("转换回字符串: %s\n", textAgain)
  187. // 自定义类型转换
  188. fmt.Println("\n自定义类型转换(温度):")
  189. freezingC := Celsius(0)
  190. freezingF := CToF(freezingC)
  191. fmt.Printf("冰点: %s = %s\n", freezingC, freezingF)
  192. boilingF := Fahrenheit(212)
  193. boilingC := FToC(boilingF)
  194. fmt.Printf("沸点: %s = %s\n", boilingF, boilingC)
  195. // rune和字符串转换
  196. chinese := "你好世界"
  197. runes := []rune(chinese)
  198. backToString := string(runes)
  199. fmt.Printf("\n中文字符串: %s\n", chinese)
  200. fmt.Printf("Rune数组: %v\n", runes)
  201. fmt.Printf("转换回字符串: %s\n", backToString)
  202. fmt.Println()
  203. }
  204. // ================================
  205. // 5. 综合应用示例
  206. // ================================
  207. // Processor 数据处理接口
  208. type Processor interface {
  209. Process() interface{}
  210. GetType() string
  211. }
  212. // StringProcessor 字符串处理器
  213. type StringProcessor struct {
  214. data string
  215. }
  216. func (sp StringProcessor) Process() interface{} {
  217. return strings.ToUpper(sp.data)
  218. }
  219. func (sp StringProcessor) GetType() string {
  220. return "string"
  221. }
  222. // IntProcessor 整数处理器
  223. type IntProcessor struct {
  224. data int
  225. }
  226. func (ip IntProcessor) Process() interface{} {
  227. return ip.data * 2
  228. }
  229. func (ip IntProcessor) GetType() string {
  230. return "int"
  231. }
  232. // processData 处理不同类型的数据
  233. func processData(processor Processor) {
  234. fmt.Printf("处理 %s 类型数据: ", processor.GetType())
  235. result := processor.Process()
  236. // 使用类型断言处理不同类型的结果
  237. switch v := result.(type) {
  238. case string:
  239. fmt.Printf("字符串结果: '%s'\n", v)
  240. case int:
  241. fmt.Printf("整数结果: %d\n", v)
  242. default:
  243. fmt.Printf("未知结果类型: %T\n", v)
  244. }
  245. }
  246. // Config 配置接口
  247. type Config interface {
  248. Validate() error
  249. Display()
  250. }
  251. // DatabaseConfig 数据库配置
  252. type DatabaseConfig struct {
  253. Host string `json:"host"`
  254. Port int `json:"port"`
  255. Username string `json:"username"`
  256. }
  257. func (dc DatabaseConfig) Validate() error {
  258. if dc.Host == "" {
  259. return errors.New("主机名不能为空")
  260. }
  261. if dc.Port <= 0 || dc.Port > 65535 {
  262. return errors.New("端口号必须在1-65535之间")
  263. }
  264. return nil
  265. }
  266. func (dc DatabaseConfig) Display() {
  267. fmt.Printf("数据库配置: Host=%s, Port=%d, Username=%s\n",
  268. dc.Host, dc.Port, dc.Username)
  269. }
  270. // loadConfig 模拟配置加载
  271. func loadConfig(configData map[string]interface{}) error {
  272. fmt.Println("\n加载配置演示:")
  273. if dbConfig, ok := configData["database"].(map[string]interface{}); ok {
  274. // 类型断言确保类型安全
  275. host, hostOk := dbConfig["host"].(string)
  276. port, portOk := dbConfig["port"].(float64) // JSON数字默认是float64
  277. username, userOk := dbConfig["username"].(string)
  278. if !hostOk || !portOk || !userOk {
  279. return errors.New("数据库配置格式错误")
  280. }
  281. config := DatabaseConfig{
  282. Host: host,
  283. Port: int(port), // 类型转换
  284. Username: username,
  285. }
  286. if err := config.Validate(); err != nil {
  287. return fmt.Errorf("数据库配置验证失败: %v", err)
  288. }
  289. config.Display()
  290. fmt.Println("✅ 数据库配置验证通过")
  291. }
  292. return nil
  293. }
  294. func demoComprehensive() {
  295. fmt.Println("5. 综合应用示例:")
  296. fmt.Println("=================")
  297. // 数据处理管道演示
  298. fmt.Println("数据处理管道:")
  299. processData(StringProcessor{"hello golang"})
  300. processData(IntProcessor{21})
  301. // 配置加载演示
  302. configData := map[string]interface{}{
  303. "database": map[string]interface{}{
  304. "host": "localhost",
  305. "port": 3306.0, // 注意JSON中的数字是float64
  306. "username": "admin",
  307. },
  308. }
  309. if err := loadConfig(configData); err != nil {
  310. fmt.Printf("配置加载错误: %v\n", err)
  311. }
  312. // 错误配置演示
  313. fmt.Println("\n错误配置演示:")
  314. badConfig := map[string]interface{}{
  315. "database": map[string]interface{}{
  316. "host": "", // 空主机名
  317. "port": 70000.0, // 无效端口
  318. "username": "admin",
  319. },
  320. }
  321. if err := loadConfig(badConfig); err != nil {
  322. fmt.Printf("❌ 配置错误: %v\n", err)
  323. }
  324. fmt.Println("\n=== 演示结束 ===")
  325. }