這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
分享出來幾個go面試題,都非常簡單,如果您有一些開發時候使用到的小技巧歡迎評論。
目前我寫出來11個(再更新一道題目),未來會不定期更新。。。
1、寫出下面代碼輸出內容。
package mainimport ("fmt")func main() {defer_call()}func defer_call() {defer func() { fmt.Println("列印前") }()defer func() { fmt.Println("列印中") }()defer func() { fmt.Println("列印後") }()panic("觸發異常")}
2、 以下代碼有什麼問題,說明原因
type student struct {Name stringAge int}func pase_student() {m := make(map[string]*student)stus := []student{{Name: "zhou", Age: 24},{Name: "li", Age: 23},{Name: "wang", Age: 22},}for _, stu := range stus {m[stu.Name] = &stu}}
3、下面的代碼會輸出什麼,並說明原因
func main() {runtime.GOMAXPROCS(1)wg := sync.WaitGroup{}wg.Add(20)for i := 0; i < 10; i++ {go func() {fmt.Println("i: ", i)wg.Done()}()}for i := 0; i < 10; i++ {go func(i int) {fmt.Println("i: ", i)wg.Done()}(i)}wg.Wait()}
4、下面代碼會輸出什嗎?
type People struct{}func (p *People) ShowA() {fmt.Println("showA")p.ShowB()}func (p *People) ShowB() {fmt.Println("showB")}type Teacher struct {People}func (t *Teacher) ShowB() {fmt.Println("teacher showB")}func main() {t := Teacher{}t.ShowA()}
5、下面代碼會觸發異常嗎?請詳細說明
func main() {runtime.GOMAXPROCS(1)int_chan := make(chan int, 1)string_chan := make(chan string, 1)int_chan <- 1string_chan <- "hello"select {case value := <-int_chan:fmt.Println(value)case value := <-string_chan:panic(value)}}
6、下面代碼輸出什嗎?
func calc(index string, a, b int) int {ret := a + bfmt.Println(index, a, b, ret)return ret}func main() {a := 1b := 2defer calc("1", a, calc("10", a, b))a = 0defer calc("2", a, calc("20", a, b))b = 1}
7、請寫出以下輸入內容
func main() {s := make([]int, 5)s = append(s, 1, 2, 3)fmt.Println(s)}
8、下面的代碼有什麼問題?
type UserAges struct {ages map[string]intsync.Mutex}func (ua *UserAges) Add(name string, age int) {ua.Lock()defer ua.Unlock()ua.ages[name] = age}func (ua *UserAges) Get(name string) int {if age, ok := ua.ages[name]; ok {return age}return -1}
9、下面的迭代會有什麼問題?
func (set *threadSafeSet) Iter() <-chan interface{} {ch := make(chan interface{})go func() {set.RLock()for elem := range set.s {ch <- elem}close(ch)set.RUnlock()}()return ch}
10、以下代碼能編譯過去嗎?為什嗎?
package mainimport ("fmt")type People interface {Speak(string) string}type Stduent struct{}func (stu *Stduent) Speak(think string) (talk string) {if think == "bitch" {talk = "You are a good boy"} else {talk = "hi"}return}func main() {var peo People = Stduent{}think := "bitch"fmt.Println(peo.Speak(think))}
11、以下代碼列印出來什麼內容,說出為什麼。。。
package mainimport ("fmt")type People interface {Show()}type Student struct{}func (stu *Student) Show() {}func live() People {var stu *Studentreturn stu}func main() {if live() == nil {fmt.Println("AAAAAAA")} else {fmt.Println("BBBBBBB")}}