MST

星途 面试题库

面试题:Go语言类型断言在复杂数据结构中的应用

有一个`interface{}`类型的切片`[]interface{} sliceI`,其中存储了多种类型的值,包括`int`、`string`和自定义结构体`type Person struct{Name string; Age int}`。请编写代码遍历这个切片,使用类型断言分别处理不同类型的值,并将`Person`类型的值的`Age`增加1 。
39.9万 热度难度
编程语言Go

知识考点

AI 面试

面试题答案

一键面试
package main

import (
    "fmt"
)

type Person struct {
    Name string
    Age  int
}

func main() {
    var sliceI []interface{}
    sliceI = append(sliceI, 10, "hello", Person{Name: "John", Age: 20})

    for _, v := range sliceI {
        switch v := v.(type) {
        case int:
            fmt.Printf("int类型的值: %d\n", v)
        case string:
            fmt.Printf("string类型的值: %s\n", v)
        case Person:
            v.Age++
            fmt.Printf("Person类型的值: Name: %s, Age: %d\n", v.Name, v.Age)
        }
    }
}