Analysis of Golang interview (IV.)

Source: Internet
Author: User
Tags sprintf
This is a creation in Article, where the information may have evolved or changed.

This is my fourth part of the Golang interview problem, if there are better topics welcome to my feedback.

31. Algorithms

The UTF8 string determines whether the specified string is included and returns the subscript. "Beijing Tian ' an door the most beautiful", "Tiananmen Square" results: 2


import ("fmt""strings")func main(){fmt.Println(Utf8Index("北京天安门最美丽", "天安门"))fmt.Println(strings.Index("北京天安门最美丽", "男"))fmt.Println(strings.Index("", "男"))fmt.Println(Utf8Index("12ws北京天安门最美丽", "天安门"))}func Utf8Index(str, substr string) int {asciiPos := strings.Index(str, substr)if asciiPos == -1 || asciiPos == 0 {return asciiPos}pos := 0totalSize := 0reader := strings.NewReader(str)for _, size, err := reader.ReadRune(); err == nil; _, size, err = reader.ReadRune() {totalSize += sizepos++// 匹配到if totalSize == asciiPos {return pos}}return pos}

32, programming

Implement a single case


package mainimport "sync"// 实现一个单例type singleton struct{}var ins *singletonvar mu sync.Mutex//懒汉加锁:虽然解决并发的问题,但每次加锁是要付出代价的func GetIns() *singleton {mu.Lock()defer mu.Unlock()if ins == nil {ins = &singleton{}}return ins}//双重锁:避免了每次加锁,提高代码效率func GetIns1() *singleton {if ins == nil {mu.Lock()defer mu.Unlock()if ins == nil {ins = &singleton{}}}return ins}//sync.Once实现var once sync.Oncefunc GetIns2() *singleton {once.Do(func() {ins = &singleton{}})return ins}

33. What happens when I execute the following code?

package mainimport ("fmt""time")func main() {ch := make(chan int, 1000)go func() {for i := 0; i < 10; i++ {ch <- i}}()go func() {for {a, ok := <-chif !ok {fmt.Println("close")return}fmt.Println("a: ", a)}}()close(ch)fmt.Println("ok")time.Sleep(time.Second * 100)}

Test Centers:Channel

Writing data to a channel that has been closed is panic. Results:

panic: send on closed channel

34. What happens when I execute the following code?

import "fmt"type ConfigOne struct {Daemon string}func (c *ConfigOne) String() string {return fmt.Sprintf("print: %v", p)}func main() {c := &ConfigOne{}c.String()}

Test centers:FMT. Sprintf

If the type implements string (), the%v and%V formats will use the value of string (). Therefore, using%V for types within a string () function of that type causes infinite recursion. Compile error:

runtime: goroutine stack exceeds 1000000000-byte limitfatal error: stack overflow

35, Programming questions

Reverses an integer that reverses an integer, for example:

Example 1:x = 123, return 321
Example 2:x = -123, return-321

The input integer requirement is a 32bit signed number, and if it overflows after inversion, the output 0

func reverse(x int) (num int) {for x != 0 {num = num*10 + x%10x = x / 10}// 使用 math 包中定义好的最大最小值if num > math.MaxInt32 || num < math.MinInt32 {return 0}return}

36, Programming questions

Merge overlapping intervals for a set of intervals, merging all overlapping intervals.

For example: given: [1,3],[2,6],[8,10],[15,18] return: [1,6],[8,10],[15,18]

type Interval struct {Start intEnd   int}func merge(intervals []Interval) []Interval {if len(intervals) <= 1 {return intervals}sort.Slice(intervals, func(i, j int) bool {return intervals[i].Start < intervals[j].Start})res := make([]Interval, 0)swap := Interval{}for k, v := range intervals {if k == 0 {swap = vcontinue}if v.Start <= swap.End {swap.End = v.End} else {res = append(res, swap)swap = v}}res = append(res, swap)return res}

37. What does it output?

package mainimport ("fmt")func main() {fmt.Println(len("你好bj!"))}

Test Center: Encoding length

Output 9

38. What happens when you compile and run the following code?

package mainimport "fmt"type Test struct {Name string}var list map[string]Testfunc main() {list = make(map[string]Test)name := Test{"xiaoming"}list["name"] = namelist["name"].Name = "Hello"fmt.Println(list["name"])}

Test Centers:Map

Programming error cannot assign to struct field list["name"].Name in map . Because list["name" is not a normal pointer value, map value itself is not addressable because the value in map is moved in memory, and the old pointer address becomes invalid when the map changes. The Var list map[string]test is defined, note OH test is not a pointer, and map we all know can be automatically expanded, then the original storage name of the Test may be at address a, but if the map expansion of address A is not the original test, So go doesn't allow us to write data. Try the var list map[string]*test instead.

Which line in 39.ABCD has errors?

type S struct {}func f(x interface{}) {}func g(x *interface{}) {}func main() {s := S{}p := &sf(s) //Ag(s) //Bf(p) //Cg(p) //D}

Test Centers:interface

The first time you see this problem is that Golang is a strongly typed language, and interface is the parent class of all golang types, like the Java object. Any type in the function func f(x interface{}) that interface{} can support incoming Golang, including pointers, but functions can func g(x *interface{}) only be accepted *interface{} .

40. What happens when you compile and run the following code?

package mainimport ("sync"//"time")const N = 10var wg = &sync.WaitGroup{}func main() {for i := 0; i < N; i++ {go func(i int) {wg.Add(1)println(i)defer wg.Done()}(i)}wg.Wait()}

Test Centers:Waitgroup

This is a mistake that is often made with Waitgroup! Please many students run will find the output will be different or even error problems. This is because go execution is too fast and execution is wg.Add(1) complete without executing the main function. Try the following instead

for i := 0; i < N; i++ {        wg.Add(1)go func(i int) {println(i)defer wg.Done()}(i)}wg.Wait()




Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.