Go language implementation integer self-increment ID generator

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

Recently need to implement a self-increment sequence of the growth function, the original practice is to achieve self-growth from the database, but the most recently used sequel Pro can not find the start from the specified value of the self-growth of the settings, only by themselves through the code to find the last item of the database and then add one, So every time you need to add data to look for, it is inconvenient, recently saw this article, benefited, the author provides the program can be directly used, ha ha, hurriedly mark, thank the author.
Original source: https://mikespook.com/2012/06/golang-channel-%E6%9C%89%E8%B6%A3%E7%9A%84%E5%BA%94%E7%94%A8/
There will be a lot of surprises when you look at the original.

package mainimport (    "fmt"    "time"    "strconv"    "reflect")type AutoInc struct {    start, step int    queue chan int    running bool}func New(start, step int) (ai *AutoInc) {    ai = &AutoInc{        start: start,        step: step,        running: true,        queue: make(chan int, 4),    }    go ai.process()    return}func (ai *AutoInc) process() {    defer func() {recover()}()    for i := ai.start; ai.running ; i=i+ai.step {        ai.queue <- i    }}func (ai *AutoInc) Id() int {    return <-ai.queue}func (ai *AutoInc) Close() {    ai.running = false    close(ai.queue)}func main() {    var ai *AutoInc    ai = New(100000,1)    for{        a :=ai.Id()        time.Sleep(5*time.Second)        b :=strconv.Itoa(a)        fmt.Println(b,reflect.TypeOf(b))    }}

Partial print Results:

100000 string100001 string100002 string

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: info-contact@alibabacloud.com 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.