當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Golang ring.Link()用法及代碼示例

Golang中的ring.Link()函數用於連接兩個環r和s環。next()函數將環r的最後一個節點連接到環s的第一個節點,因此r.next()不能為空。否則,將引發錯誤。它的工作方式類似於循環鏈表。

用法:

func (r *Ring) Link(s *Ring) *Ring

它不返回任何東西。

範例1:

// Golang program to illustrate 
// the ring.Link() function 
package main 
  
import ( 
    "container/ring"
    "fmt"
) 
  
// Main function 
func main() { 
  
    // Create two rings, a and b, of size 2 
    a:= ring.New(4) 
    b:= ring.New(4) 
  
    // Get the length of the ring 
    m:= a.Len() 
    n:= b.Len() 
  
    // Initialize a with 0s 
    for j:= 0; j < m; j++ { 
        a.Value = 0 
        a = a.Next() 
    } 
  
    // Initialize b with 1s 
    for i:= 0; i < n; i++ { 
        b.Value = 1 
        b = b.Next() 
    } 
  
    // Link ring a and ring b 
    ab:= a.Link(b) 
  
    ab.Do(func(p interface{}) { 
        fmt.Println(p.(int)) 
    }) 
  
}

輸出:

0
0
0
0
1
1
1
1

範例2:

// Golang program to illustrate 
// the ring.Link() function 
package main 
  
import ( 
    "container/ring"
    "fmt"
) 
  
// Main function 
func main() { 
  
    // Create two rings, r and s, of size 2 
    r:= ring.New(2) 
    s:= ring.New(2) 
  
    // Get the length of the ring 
    lr:= r.Len() 
    ls:= s.Len() 
  
    // Initialize r with "GFG" 
    for i:= 0; i < lr; i++ { 
        r.Value = "GFG"
        r = r.Next() 
    } 
  
    // Initialize s with "COURSE" 
    for j:= 0; j < ls; j++ { 
        s.Value = "COURSE"
        s = s.Next() 
    } 
  
    // Link ring r and ring s 
    rs:= r.Link(s) 
  
    // Iterate through the combined 
    // ring and print its contents 
    rs.Do(func(p interface{}) { 
        fmt.Println(p.(string)) 
    }) 
}

輸出:

GFG
GFG
COURSE
COURSE



相關用法


注:本文由純淨天空篩選整理自vipinyadav15799大神的英文原創作品 ring.Link() Function in Golang With Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。